home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 23 / CU Amiga - Super CD-ROM 23 (June 1998).iso / CreatingGames / GameCreators / Inform / technical_manual.txt < prev    next >
Encoding:
Text File  |  1997-03-15  |  320.5 KB  |  7,246 lines

  1. ------------------------------------------------------------------------------
  2.                                Inform 6.14
  3.  
  4.                             Technical  Manual
  5.  
  6.                               Graham Nelson
  7.                              27th April 1996
  8.                       revised on the following dates:
  9.     5th May, 10th May, 6th September, 23rd September, 16th December 1996,
  10.            27th January 1997, 26th March, 5th April, 8th September
  11. ------------------------------------------------------------------------------
  12.     1   The source code
  13.             1.1   Inventory
  14.             1.2   Map
  15.             1.3   Naming conventions
  16.             1.4   Typedef-named types
  17.     2   Porting Inform to a new environment
  18.             2.1   Dependence on the OS
  19.             2.2   Portability issues: the types int32 and uchar
  20.             2.3   The character set and the format of text files
  21.             2.4   The OS definitions block in "header.h"
  22.             2.5   Running Inform in a multi-tasking OS
  23.     3   Front end
  24.             3.1   The ICL interpreter
  25.             3.2   Fundamental method
  26.     4   Lexical analysis
  27.             4.1   Aim and structure of the lexer
  28.             4.2   Level 1: lexical blocks and buffered input
  29.             4.3   Level 2: breaking text into lexemes
  30.             4.4   Representation of tokens
  31.             4.5   Level 3: identifying identifiers
  32.             4.6   Hash-coding and comparing names
  33.             4.7   The symbols table
  34.             4.8   Token lookahead: the circle
  35.             4.9   Summary of the token output
  36.     5   Syntax analysis 1: the top-down structural parser
  37.             5.1   Aim and structure of the syntax analyser
  38.             5.2   Predictive parsing
  39.             5.3   The context-free grammar
  40.             5.4   Assigning values to symbols
  41.             5.5   Outputs other than assembly language
  42.             5.6   Assembly operands
  43.             5.7   Translation to assembly language
  44.             5.8   Summary of assembly language instructions output
  45.     6   Syntax analysis 2: the bottom-up expression parser
  46.             6.1   Map and structure
  47.             6.2   The operator precedence grammar
  48.             6.3   Lexical level 4: tokens to etokens
  49.             6.4   Resolution of ambiguous tokens
  50.             6.5   Constant folding
  51.             6.6   Checking lvalues and simplifying the parse tree
  52.             6.7   Summary of parse tree output
  53.     7   Code generation from parse trees
  54.             7.1   Aim and structure of the code generator
  55.             7.2   Annotation for conditions
  56.             7.3   Main traversal
  57.             7.4   Void context
  58.             7.5   Results of subexpressions
  59.             7.6   Conditional and logical operators
  60.             7.7   System functions
  61.     8   Assembly of code, text and data structures
  62.             8.1   Assembly of initial code
  63.             8.2   Branch offset backpatching and optimisation
  64.             8.3   Text translation: ISO and Unicode resolution
  65.             8.4   Dictionary management
  66.             8.5   Format of tables unspecified by the Z-machine
  67.             8.6   Grammar version numbers GV1 and GV2
  68.             8.7   Value backpatching
  69.             8.8   Packed address decoding
  70.     9   Run-time veneer
  71.             9.1   Services provided by the veneer
  72.             9.2   Properties 2 and 3, "ofclass" and "metaclass"
  73.             9.3   Class numbering and class objects
  74.             9.4   Individual property identifiers
  75.             9.5   Individual property tables
  76.             9.6   Availability of symbol names at run-time
  77.     10  Module compilation and linking
  78.             10.1  Model
  79.             10.2  Linking a module
  80.             10.3  Imports and exports
  81.             10.4  Backpatch backpatching
  82.             10.5  How modules differ from story files
  83.             10.6  Restrictions on what modules may contain
  84.     11  Service levels
  85.             11.1  Variables and arrays
  86.             11.2  Memory allocation and deallocation
  87.             11.3  Error messages
  88.             11.4  File input/output
  89.     12  Low-level language features
  90.             12.1  Using the "Trace" directive
  91.             12.2  System constants and other secret syntaxes
  92.             12.3  The "Zcharacter" directive
  93.             12.4  Sequence points
  94.             12.5  Format of debugging information files (for Infix)
  95.     13  What little I remember
  96.             13.1  Publication history
  97.             13.2  Design history
  98.             13.3  Implementation history
  99.             13.4  Modification history
  100. ------------------------------------------------------------------------------
  101.  
  102.     1   The source code
  103.         ---------------
  104.  
  105.     1.1   Inventory
  106.           ---------
  107.  
  108. Inform is written in portable ANSI C and the source code is divided into 21
  109. files of code, called "sections", plus 1 #include file of linkage, constant
  110. and type definitions.  These files are:
  111.  
  112.   arrays.c     asm.c        bpatch.c     chars.c      directs.c    errors.c
  113.   expressc.c   expressp.c   files.c      inform.c     lexer.c      linker.c
  114.   memory.c     objects.c    states.c     symbols.c    syntax.c     tables.c
  115.   text.c       veneer.c     verbs.c      header.h
  116.  
  117. Note that all their names fit into the 8.3 filenaming convention.  The
  118. subdivision into 21 sections is intended to ensure that each .c file can be
  119. compiled into one linkable object file: under some C compilers object
  120. code files cannot exceed 64K in length.  On my machine, expressc.o (the
  121. object code derived from expressc.c) is the largest, at 40K (about a third of
  122. which is the static table of operator data).
  123.  
  124. A concise tree giving the structure of the source code follows.  A section
  125. name is given brackets when it has already been given on a previous line: so
  126. "(inform.c)" is intended to be read as "now back to inform.c again". A name
  127. written as a function, like "compile()", is indeed a function, whose
  128. arguments are omitted here.  Text in square brackets indicates the presence
  129. of interesting tables of static data.  Finally, note that this structure
  130. is not absolutely rigorous: the error-reporting routines in "errors.c", for
  131. example, are called from all over Inform, not just from the lexical analyser.
  132.  
  133.  
  134.     inform.c  ICL parser: switches, filename translation, path variables
  135.  
  136.     memory.c  ICL memory command parser: sets memory settings.
  137.  
  138.     (inform.c)   compile(): polling all sections to manage variables,
  139.                  allocate and free arrays
  140.  
  141.     syntax.c       syntax analyser, top level
  142.     
  143.     lexer.c          lexical analyser: converts source text to a stream of
  144.                      tokens
  145.                      [Tables of all Inform keywords]
  146.  
  147.     chars.c            performs character set translations
  148.     
  149.     files.c            reads source code files into buffers for the lexer;
  150.                        performs miscellaneous file I/O
  151.  
  152.     symbols.c          keeps table of symbol names found in the source;
  153.                        recognises from and adds to this table
  154.     
  155.     errors.c           issues error, fatal error and warning messages
  156.     
  157.     (syntax.c)     parse_program(): top level routine in syntax analyser
  158.  
  159.                      parse_directive()
  160.  
  161.     directs.c          parse_given_directive(): parses and obeys the easier
  162.                        directives; manages conditional compilation; delegates
  163.                        directive parsing down to other sections for harder
  164.                        cases:
  165.  
  166.     text.c               make_abbreviation(): Abbreviate
  167.  
  168.     arrays.c             make_global(): Array, Global
  169.  
  170.     objects.c            make_attribute(): Attribute
  171.                          make_property(): Property
  172.                          make_class(): Class
  173.                          make_object(): Object
  174.  
  175.     verbs.c              make_fake_action(): Fake_Action
  176.                          make_verb(): Verb
  177.                          extend_verb(): Extend
  178.  
  179.     linker.c             link_module(): Link
  180.  
  181.     (symbols.c)            assign_symbol(): giving value and type to symbols
  182.  
  183.     (syntax.c)         parse_routine()
  184.  
  185.                          parse_code_block()
  186.  
  187.     states.c               parse_statement(): assigns ".Label" labels, parses
  188.                            and generates code for statements
  189.  
  190.                              parse_action(): handles <Action ...> statements
  191.  
  192.                              parse_print(): handles print and print_ret
  193.  
  194.     asm.c                    parse_assembly(): handles assembly language
  195.                              source code (preceded by "@")
  196.  
  197.     expressp.c                 parse_expression(): parses all expressions
  198.                                (including constants), conditions and
  199.                                assignments.
  200.  
  201.     expressc.c                 [Table of operators]
  202.                                code_generate(): generates code from parse
  203.                                trees previously found by parse_expression()
  204.  
  205.     (asm.c)                      assemble_2_to() (and many other similarly
  206.                                  named routines)
  207.  
  208.                                    [Database of all Z-machine opcodes]
  209.                                    assemble_instruction(): assembles a single
  210.                                    Z-code instruction
  211.  
  212.                                    assemble_label_no(): puts label N here
  213.  
  214.                                    assemble_routine_end(): finishes routine,
  215.                                    backpatches and optimises branches
  216.  
  217.     (text.c)                     compile_string(): translates ASCII text
  218.                                  to Z-encoded text
  219.  
  220.                                  the dictionary manager
  221.  
  222.                                  the abbreviations optimiser
  223.  
  224.     (chars.c)                      performs character set translations
  225.  
  226.     veneer.c       compile_veneer(): compiles in any whole routines
  227.                    needed by the rest of the compiled code
  228.                    [Table of Inform source code for veneer routines]
  229.  
  230.     tables.c       construct_storyfile(): glues together all the
  231.                    code, dictionary, object tree, etc. into a story file
  232.  
  233.     bpatch.c       backpatch the code in the light of recent knowledge
  234.  
  235.  
  236.     1.2   Map
  237.           ---
  238.  
  239. Here follows a map of the Inform archipelago, marking the inhabited islands,
  240. their shipping lanes and chief imports and exports:
  241.  
  242.  
  243.          command line
  244.        and/or ICL files in
  245.               |
  246.               | ICL commands
  247.              \|/
  248.          +----------+ FRONT
  249.          | inform.c | END
  250.          | memory.c |
  251.          +----------+
  252.               |
  253.               | filenames
  254.               |
  255.              \|/          +------------+ LEXICAL
  256.   ------>  files.c -----> | lexer.c    | ANALYSER
  257.   source            chars | symbols.c  |
  258.   code in                 +------------+
  259.                               /|\  |
  260.                         symbol |   |
  261.                         values |   | tokens
  262.                                |  \|/
  263.                           +------------+
  264.                SYNTAX     | syntax.c   | -----+------>  asm.c  --->---\
  265.                ANALYSER:  | states.c   |     /  assembly /|\   initial|
  266.                STATEMENTS |     .      |    /    language |       code|
  267.                           | ---------- |   /              |           |
  268.                @ ASSEMBLY | asm.c      | -/               |           |
  269.                           | ---------- |                  |           |
  270.                           |     .      | parse trees      |          \|/
  271.               EXPRESSIONS | expressp.c | --+-------> expressc.c     asm.c
  272.                           |  (map 6.1) |    \                         |
  273.                           |     .      |     \                        |
  274.                           |     .      |      \         TEXT          |
  275.                           | ---------- |    strings   +-------+Z-text |
  276.                DIRECTIVES | directs.c  |        \---->|text.c |-->---)|(--\
  277.                           |     .      |              |chars.c|       |   |
  278.                           |     .      |              +-------+       |   |
  279.                           |     .      |        dictionary|           |   |
  280.                           |     .      |       alphabets \|/         \|/  |
  281.                           |     .      |                  |           |   |
  282.                           | arrays.c   | ------->------\  |           |   |
  283.                           |     .      |  array area   |  |        raw|   |
  284.                           |     .      |               |  |     Z-code|   |
  285.                           | objects.c  | ----->-----\  |  |           |   |
  286.                           | verbs.c    |  objects   |  |  |           |   |
  287.                           +------------+            |  |  |           |   |
  288.                                 |                  \|/\|/\|/         \|/  |
  289.                                 |    grammar      +----------+----------+ |
  290.                                 \---------------> | tables.c   bpatch.c | |
  291.                                                   +----------+----------+ |
  292.                                                        |    OUTPUT    |   |
  293.                                                        |              |   |
  294.                                             Z-machine \|/       Z-code|   |
  295.                                                  up to |              |   |
  296.                                              code area |             \|/ \|/
  297.                                                        \-----------> files.c
  298.                                                                         |
  299.                                                                         |
  300.                                                                        \|/
  301.                                                                       story
  302.                                                                     file out
  303.  
  304. (For clarity, the linker and a few smaller tables are missed out; and the
  305. "service" sections of Inform, such as "errors.c" and the allocation code in
  306. "memory.c", are missed out since they are, so to speak, pipes and sewers
  307. which lie beneath the surface of the ocean.)
  308.  
  309.  
  310.     1.3   Naming conventions
  311.           ------------------
  312.  
  313. The "header.h" makes over 700 constants using #define.
  314.  
  315. These are mainly in capital letters and are followed by _ and then some short
  316. code indicating what kind of constant is being defined: for instance,
  317. NUMBER_TT means "the token type <number>".  We write *_TT for the set of
  318. constants ending in _TT.  Similarly, though to a lesser extent, groups of
  319. related variables and routines have grouped names.
  320.  
  321.     -------------------------------------------------------------------------
  322.     Set of constants          Used for
  323.     -------------------------------------------------------------------------
  324.     *_Extension               File extensions, such as ".z5", used if the
  325.                               host OS supports them
  326.     *_Directory               Initial values for the ICL path variables
  327.                               (e.g., default pathname where story files are
  328.                               written to)
  329.  
  330.     *_TT                      Token types
  331.  
  332.     *_CODE                    Token values for statement and directive names
  333.     *_COND                    Token values for textual condition names
  334.     *_SEGMENT                 Token values for object definition segment names
  335.     *_MK                      Token values for misc statement keywords
  336.     *_TK                      Token values for "trace" directive keywords
  337.     *_DK                      Token values for misc directive keywords
  338.     *_SC                      Token values for system constant names
  339.                               (* is written in lower case)
  340.     *_SYSF                    Token values for system function names
  341.                               [In all of the above eight cases, * is the name
  342.                               of the statement, keyword, etc. referred to,
  343.                               written in upper case except as specified above]
  344.  
  345.     *_SEP                     Token values for separators
  346.                               (the name sometimes reflects the text, e.g.,
  347.                               DARROW_SEP for the double-length arrow "-->";
  348.                               sometimes its use, e.g. NOTEQUAL_SEP for "~=")
  349.  
  350.     *_OP                      Token values for operators
  351.     *_A                       Associativity values for operators
  352.     *_U                       "Usage" (infix, prefix or postfix) values for
  353.                               operators
  354.  
  355.     *_T                       Symbol types
  356.     *_SFLAG                   Symbol flags
  357.                               (bitmasks containing one bit set, so that
  358.                               (sflags[i] & *_SFLAG) is true if flag is set)
  359.  
  360.     *_CONTEXT                 Contexts in which the expression evaluator
  361.                               can run (e.g., "void", "condition")
  362.  
  363.     *_zc                      Internal numbers referring to Z-machine opcodes
  364.                               (* is the Standard 0.2 name for the opcode,
  365.                               written in lower case)
  366.     *_OT                      Assembly operand types
  367.     *_STYLE                   Two constants used to set whether the Z-machine
  368.                               has "time" or "score/moves" on its status line
  369.     *_ZA                      Z-machine areas: e.g. PROP_ZA refers to the
  370.                               property values table area
  371.     *_MV                      Marker values
  372.     *_VR                      Veneer routines (* is the name of the routine,
  373.                               usually in mixed case)
  374.  
  375.     *_DBR                     Record types in debugging information files
  376.  
  377.     -------------------------------------------------------------------------
  378.     Set of variables          Used for
  379.     -------------------------------------------------------------------------
  380.     *_switch                  Flag indicating whether a command-line switch
  381.                               such as -s is on or off
  382.     *_setting                 Numerical value set by a command-line switch
  383.                               such as -t3
  384.     MAX_*                     A limit on something: note that a few of these
  385.                               are #define'd but most are memory setting
  386.                               variables
  387.     no_*                      Number of things of this type made so far
  388.     max_*                     Maximum number of things of this type made
  389.     token_*                   Three variables used to hold the value, type
  390.                               and lexeme text for the last token read
  391.     *_trace_level             0 if tracing information is not being printed
  392.                               out about *; otherwise, the larger this is,
  393.                               the more output is produced
  394.     *_offset                  Byte offset in the Z-machine, either from the
  395.                               start of this Z-machine area or from the start
  396.                               of Z-machine memory
  397.     *_top                     Pointer marking the current end in some uchar
  398.                               array (usually holding a Z-machine area being
  399.                               put together)
  400.  
  401.     -------------------------------------------------------------------------
  402.     Set of routines           Used for
  403.     -------------------------------------------------------------------------
  404.     init_*_vars()             Routine in which section * of Inform initialises
  405.                               its variables to begin compilation
  406.     *_begin_pass()            ...and in which it initialises its variables
  407.                                  at the start of the source code pass
  408.     *_allocate_arrays()       ...and in which is allocates any memory or
  409.                                  arrays it needs to begin compilation
  410.     *_free_arrays()           ...and in which it deallocates any memory or
  411.                                  arrays it has allocated, after compilation
  412.     parse_*()                 Routine in the syntax analyser to parse the
  413.                               source code construct *
  414.     assemble_*()              Instructing the assembler to generate an
  415.                               instruction:
  416.     assemble_#()              (where # is a number from 0 to 4) an instruction
  417.                               with # operands
  418.     assemble_#_to()           an instruction with #operands which stores a
  419.                               result
  420.     assemble_#_branch()       an instruction with #operands which makes a
  421.                               conditional branch
  422.     *_linenum()               Keeping and writing line references to the
  423.                               debugging information file
  424.  
  425.  
  426.     1.4   Typedef-named types
  427.           -------------------
  428.  
  429.     -------------------------------------------------------------------------
  430.     Typedef name      Where defined      Used for
  431.     -------------------------------------------------------------------------
  432.     int32                  H             signed 32-bit integer
  433.     uint32                 H             unsigned 32-bit integer
  434.     uchar                  H             unsigned char
  435.  
  436.     assembly_operand       H             holding Z-machine numbers in the form
  437.                                          used in Z-code, together with linkage
  438.                                          information about how they were
  439.                                          calculated
  440.     assembly_instruction   H             a convenient representation of an
  441.                                          instruction of Z-code to assemble
  442.     opcode                 asm.c         everything about a Z-machine opcode:
  443.                                          how many operands it has, whether
  444.                                          branch or store, etc.
  445.     verbl                  H             grammar line of 8 token values
  446.     verbt                  H             grammar table of grammar lines
  447.     prop                   H             list of values for a property
  448.     propt                  H             property values table
  449.     fpropt                 H             the same, but with attributes too
  450.     objectt                H             object tree-position and attributes
  451.     dict_word              H             Z-text of a dictionary word
  452.     dbgl                   H             source code reference used for the
  453.                                          debugging file (to file, line, char)
  454.     keyword_group          H             the plain text of a group of keywords
  455.                                          (such as: all the statement names)
  456.     token_data             H             lexical tokens
  457.     expression_tree_node   H             node in a parse tree produced by
  458.                                          the section "expressp.c"
  459.     operator               H             everything about an operator: its
  460.                                          name, how to recognise it, its usage
  461.                                          and associativity, etc.
  462.  
  463.     memory_block           H             an extensible area of memory
  464.                                          (allocated in 8K chunks as required)
  465.  
  466.     tlb_s                  text.c        used in abbreviations optimiser
  467.     optab_s                text.c        used in abbreviations optimiser
  468.  
  469.     FileId                 H             filename and handle for a source file
  470.     ErrorPosition          H             filename and line reference for
  471.                                          error message printing purposes
  472.     LexicalBlock           lexer.c       name, line count, etc.
  473.                                          within a block of text being lexed
  474.     Sourcefile             lexer.c       buffer, pipeline and lexical block
  475.                                          for a source code file being lexed
  476.     ImportExport           linker.c      holds import/export records
  477.     Marker                 linker.c      holds marker records
  478.     VeneerRoutine          veneer.c      holds low-level Inform source code
  479.                                          for a veneer routine
  480.     -------------------------------------------------------------------------
  481.                                    "H" is an abbreviation here for "header.h"
  482.  
  483.  
  484.     2   Porting Inform to a new environment
  485.         -----------------------------------
  486.  
  487.     2.1   Dependence on the OS
  488.           --------------------
  489.  
  490. Strenuous efforts have been made over the last three years to make the source
  491. as operating-system independent as possible.  As a general principle, mostly
  492. adhered to, all operating-system differences should be in the "header.h"
  493. file, and not in the 20 sections.
  494.  
  495. As a general rule, for each target OS which Inform is being ported to, a new
  496. #define name is invented.  For example, the name LINUX is used for the Linux
  497. port.  When Inform is being compiled, only that one symbol will be defined,
  498. and none of the others: thus
  499.  
  500. #ifdef LINUX
  501.    ...code...
  502. #endif
  503.  
  504. compiles the given code only for the Linux port.
  505.  
  506. There are some very poor "ANSI C" compilers out there, and many more mediocre
  507. ones (which almost obey the standard, but don't quite): in any case the ANSI
  508. standard is very broadly defined.  For example, the code
  509.  
  510. int x;
  511. x = 45*1007;
  512. printf("%d\n", x);
  513.  
  514. is entirely ANSI compliant, but results in different numbers being printed
  515. on different machines, due to the fact that ANSI does not specify the range
  516. of numbers which a variable of type int can safely hold.  Since C is so highly
  517. unportable a language, and since some of the compilers used to produce Inform
  518. are poor, the whole Inform code has to be written with the worst possible
  519. compiler in mind.
  520.  
  521. An illustration of this is that all preprocessor commands, such as #define,
  522. must begin on column 1 of the source code: even when they occur in code which
  523. is #ifdef'd out.  VAX C (a particularly bad compiler) will reject
  524.  
  525. #ifndef VAX
  526.   #define FROG 2
  527. #endif
  528.  
  529. for example, even when VAX is defined.  This makes the declarations in
  530. "header.h" annoyingly illegible for everybody.
  531.  
  532.  
  533.     2.2   Portability issues: the types int32 and uchar
  534.           ---------------------------------------------
  535.  
  536. The main issues when porting Inform have been found to be:
  537.  
  538.     (a) the size of "int",
  539.     (b) whether "char" is unsigned or signed by default,
  540.     (c) what conventions apply to filenames,
  541.     (d) assumptions about sizeof() when casting pointers,
  542.     (e) how parameters (switches, filenames, etc.) are passed to Inform.
  543.  
  544. (a) ANSI requires that "int" be at least 16 bit, though advances in CPU
  545.     technology mean that under most of today's environments it will in fact be
  546.     32 bit.  ANSI further requires that "long int" be at least as big as "int",
  547.     but not that it has to be any bigger.
  548.  
  549.     Inform needs at least one integer type to be able to hold 32 bit signed
  550.     values, and "header.h" contains code which attempts to typedef the name
  551.     "int32" to such a type.  This should happen automatically.
  552.     
  553.     Under ANSI rules, as the above says, a compiler need not have any integer
  554.     type larger than 16 bits: if so, that compiler will not be able to
  555.     compile Inform.
  556.  
  557.     An annoying issue here is that compilers vary widely in the extent to
  558.     which they give errors or warnings when they detect silent "promotions"
  559.     from one integer type to another.  This makes it very hard to sort out
  560.     the types of every object in the program between int and int32 so that
  561.     everybody is happy: in practice, every time a new release of the source
  562.     code has been made, a few dozen types have had to be fiddled with until
  563.     everybody can compile it.
  564.  
  565. (b) Compilers seem to divide about fifty-fifty on this.  Again, the original
  566.     standard is vague: the issue is really about how the value (char) 253,
  567.     say, should be interpreted when it is cast to (int).  Should the answer
  568.     be 253, or -3?  ANSI did not specify this because compiler writers
  569.     wanted to be able to choose whichever could be done instantly on the
  570.     CPUs they were working with.  (If you store a char in the bottom 8 bits
  571.     of a 32 bit register, then casting the value (char) 253 to (int) -3
  572.     means setting all 24 of the upper bits, which requires code to be
  573.     compiled.)
  574.  
  575.     Inform uses a typedef'd type called "uchar" when it needs an unsigned
  576.     char type: it uses plain "char" when it doesn't mind.  It never needs
  577.     a signed char type.
  578.     
  579.     In theory ANSI C compilers must recognise the keywords "signed" and
  580.     "unsigned", but some don't:
  581.     
  582.         typedef unsigned char uchar;
  583.  
  584.     actually produces an error on some compilers.  So the typedef can only
  585.     be made with your help.  (On other compilers, "unsigned" is legal but
  586.     "signed" is illegal.)
  587.     
  588. (c) Many people think that the minimal 8.3 convention will work on any
  589.     operating system, but this is not true (it won't work under Acorn's
  590.     RISC OS).  Much of each OS specification in "header.h" is therefore
  591.     to do with filenaming.
  592.  
  593. (d) For instance,
  594.  
  595.         sizeof(char *)    sizeof(int *)    sizeof(int32 *)    sizeof(int)
  596.  
  597.     may all be different numbers on machines with segmented memory maps.
  598.     This being so, casting between pointer types may lose information, and
  599.     a few arrays in the source have surprising types to ensure safety.
  600.  
  601.     One thing Inform does need to be able to do is to subtract one pointer
  602.     (of the same type) from another: it defines the macro
  603.     
  604.         subtract_pointers(X, Y)
  605.  
  606.     to do this.  X and Y are normally of type uchar; there seems to have been
  607.     no problem with this in practice.
  608.  
  609. (e) The ANSI standard is quite good on the command line, and Inform expects
  610.     to read parameters by the standard argc, argv mechanism.  Unfortunately
  611.     the Macintosh, for instance, has no orthodox command line.  Such a port
  612.     probably wants to have an "outer shell" which displays a window, allows
  613.     options to be set and then calls the Inform 6 core as needed.
  614.  
  615.     The section "inform.c" normally compiles a "main" routine which makes
  616.     a few machine-dependent changes and then passes its arguments straight
  617.     on to "sub_main".  For instance, here's the v6.10 source:
  618.  
  619.         int main(int argc, char **argv)
  620.         {   int rcode;
  621.             #ifdef MAC_MPW
  622.             InitCursorCtl((acurHandle)NULL); Show_Cursor(WATCH_CURSOR);
  623.             #endif
  624.             rcode = sub_main(argc, argv);
  625.             #ifdef ARC_THROWBACK
  626.             throwback_end();
  627.             #endif
  628.             return rcode;
  629.         }
  630.  
  631.     The Macintosh Programmer's Workshop port is making multi-tasking
  632.     work before embarking on compilation; the Acorn Desktop Debugging
  633.     Environment port is tidying up after any error throwbacks, at the
  634.     end of compilation.  The point is that here is the place for such
  635.     minor machine quirks.
  636.  
  637.     However, if you want an entirely new front end (such as Robert Pelak's
  638.     Macintosh port of Inform has), then you need to define
  639.     
  640.         #define EXTERNAL_SHELL
  641.  
  642.     in your machine definition block (see later).  This will mean that
  643.     no "main" routine is compiled at all from "inform.c" (so you can
  644.     simply link the Inform source into your own code, which will
  645.     contain its own "main.c"): Inform should be run by calling
  646.     
  647.         extern int sub_main(int argc, char **argv);
  648.  
  649.     having set up argc and argv suitably.  For instance, the outer shell
  650.     might take names typed into dialogue boxes, and various ticked options
  651.     on a window, and make these into a series of ICL commands, which
  652.     are then handed over textually to sub_main.  I suggest that the most
  653.     efficient way to do this is to write them as an ICL file somewhere
  654.     and to pass sub_main a single parameter telling it to run this
  655.     ICL file.
  656.  
  657.  
  658.     2.3   The character set and the format of text files
  659.           ----------------------------------------------
  660.  
  661. The Inform source code assumes that the compiler is running on a machine
  662. whose character set agrees with ASCII in the range $20 to $7e.  (This
  663. allows both plain ASCII and any of the ISO 8859 extensions to ASCII.)
  664.  
  665. ASCII is now universal, but there is no common format for plain text files,
  666. and in particular how lines of text are ended.  For example:
  667.  
  668.     MS-DOS, Windows, etc.:  $0d $0a
  669.     Mac OS:                 $0d
  670.     RISC OS:                $0a
  671.  
  672. Inform 6 can read source code files in all these formats, and which further
  673. use any of the character sets above: plain ASCII or ISO 8859-1 to -9.
  674. (This is configurable using the -C switch.)
  675.  
  676.  
  677.     2.4   The OS definitions block in "header.h"
  678.           --------------------------------------
  679.  
  680. Each Inform port makes a block of definitions in the header file.  These
  681. blocks take a standard format.
  682.  
  683. Firstly, the block is put in #ifdef's so that it will only be processed
  684. in this one port.  The block is divided into 6 sections, as follows.
  685.  
  686.     /* 1 */
  687.  
  688.     MACHINE_STRING should be set to the name of the machine or OS.
  689.  
  690.     /* 2 */
  691.  
  692.     Section 2 contains some miscellanous options, all of which are on/off:
  693.     they are by default off unless defined.  The possibilities are:
  694.  
  695.       USE_TEMPORARY_FILES - use scratch files for workspace, not memory,
  696.                             by default
  697.       EXTERNAL_SHELL      - this port is providing an entire external
  698.                             front end, with its own "main" routine:
  699.                             see above
  700.       PROMPT_INPUT        - prompt input: ignore argc and argv, instead
  701.                             asking for parameters at the keyboard.
  702.                             (I hope people will write front-ends
  703.                             rather than resort to this, but it may be
  704.                             a useful staging post.)
  705.       TIME_UNAVAILABLE    - if the ANSI library routines for working out
  706.                             today's date are not available
  707.       CHAR_IS_SIGNED      - if on your compiler the type "char" is signed
  708.                             by default
  709.  
  710.     Note that defining USE_TEMPORARY_FILES does not make a mandatory choice
  711.     (as it did under Inform 5): whether to use allocated memory or temporary
  712.     files is selectable with -F0 (files off) or -F1 (files on) in ICL.
  713.     All that this option does is to define the default setting for this -F
  714.     switch.
  715.  
  716.     Running -F0 is faster (possibly, depending on whether your C library
  717.     provides buffering or not, much faster) but consumes 100 to 300K more
  718.     memory (it does so flexibly, allocating only what it needs, unlike the
  719.     Inform 5 option).  Most users will not want to understand the issues
  720.     involved here, so please make a sensible default choice for them.
  721.  
  722.     Once again, note that CHAR_IS_SIGNED must be defined if "char" is signed:
  723.     otherwise "uchar" will be typedef'd wrongly.
  724.  
  725.     /* 3 */
  726.  
  727.     An estimate of the typical amount of memory likely to be free should be
  728.     given in DEFAULT_MEMORY_SIZE.  (This is only a default setting.)
  729.     
  730.     There are three settings: HUGE_SIZE, LARGE_SIZE and SMALL_SIZE.
  731.     (I think it was Andrew Plotkin, though, who remarked that HUGE_SIZE
  732.     might sensibly be renamed "not-bad-by-1980s-standards-size":
  733.     these all allocate quite small amounts of memory compared to, say,
  734.     the 8M of workspace that Windows appears to need just to keep breathing.)
  735.  
  736.     For most modern machines, LARGE_SIZE is the appropriate setting, but
  737.     some older micros may benefit from SMALL_SIZE.
  738.  
  739.     /* 4 */
  740.  
  741.     This section specifies the filenaming conventions used by the host OS.
  742.  
  743.     It's assumed that the host OS has the concept of subdirectories and
  744.     has "pathnames", that is, filenames giving a chain of subdirectories
  745.     divided by the FN_SEP (filename separator) character: e.g. for Unix
  746.     FN_SEP is defined below as '/' and a typical name is
  747.  
  748.                           users/graham/jigsaw.z5
  749.  
  750.     Normally the comma ',' character is used to separate pathnames in a
  751.     list of pathnames, but this can be overridden by defining FN_ALT
  752.     as some other character.  Obviously it should be a character which never
  753.     occurs in normal pathnames.
  754.                                                                            
  755.     If FILE_EXTENSIONS is defined then the OS allows "file extensions" of
  756.     1 to 3 alphanumeric characters like ".txt" (for text files), ".z5"
  757.     (for game files), etc., to indicate the file's type (and, crucially,
  758.     regards the same filename but with different extensions -- e.g.,
  759.     "frog.amp" and "frog.lil" -- as being different names).
  760.  
  761.     If FILE_EXTENSIONS is defined, then Inform uses the following standard
  762.     set of extensions unless they are overridden by other definitions
  763.     at this point.  (Please don't override these definitions without reason.)
  764.  
  765.         Source_Extension  ".inf"    Source code file
  766.         Include_Extension ".h"      Include file (e.g. library file)
  767.  
  768.         Code_Extension    ".z3"     Version 3 story file
  769.         V4Code_Extension  ".z4"             4
  770.         V5Code_Extension  ".z5"             5
  771.         V6Code_Extension  ".z6"             6
  772.         V7Code_Extension  ".z7"             7
  773.         V8Code_Extension  ".z8"             8
  774.  
  775.         Module_Extension  ".m5"     Linkable module file (version 5,
  776.                                     which is all that Inform 6 supports yet)
  777.  
  778.         ICL_Extension     ".icl"    ICL file
  779.  
  780.     The debugging information file and the transcript file also have defined
  781.     default-names which can be over-ridden in this section if desired:
  782.     
  783.         Transcript_File   "gametext.txt" or "gametext"
  784.         Debugging_File    "gameinfo.dbg" or "gamedebug"
  785.  
  786.     If you do not define FILE_EXTENSIONS, then it is essential to define
  787.     STANDARD_DIRECTORIES instead.  (You can also define both, if you so
  788.     choose.)
  789.  
  790.     The STANDARD_DIRECTORIES option causes Inform to put all files of
  791.     a particular kind into a standard directory for them: e.g., a "games"
  792.     directory might hold the story files compiled, etc.  All that happens
  793.     when a standard directory is defined is that Inform sets the default
  794.     value of the relevant pathname variable to that standard directory:
  795.     otherwise, its pathname variable starts out as "".
  796.                                                                            
  797.     The standard directories are, once again, defined by default as follows:
  798.     once again you can define these settings yourself, but please don't
  799.     do so without a good reason.
  800.  
  801.         Source_Directory      "source"
  802.         Include_Directory     "library"
  803.         Code_Directory        "games"
  804.         Module_Directory      "modules"
  805.         Temporary_Directory   ""
  806.         ICL_Directory         ""
  807.  
  808.     Note that the actual user of Inform can still override anything you
  809.     choose by setting the pathname with an ICL command.
  810.  
  811.     A good way to test all this is to run inform -h1, which does some
  812.     experimental filename translations and prints the outcome.
  813.  
  814.     /* 5 */
  815.  
  816.     Section 5 contains information on how to choose the filenames for the
  817.     three temporary files.  (Note that this needs to be done even if
  818.     USE_TEMPORARY_FILES is not defined.)
  819.  
  820.     On many machines, you only need to give a suitable name.  (As usual,
  821.     if you don't bother, something fairly sensible happens.)
  822.  
  823.     Temporary_Name is the body of a filename to use (if you don't set this,
  824.     it becomes "Inftemp") and Temporary_Directory is the directory path for
  825.     the files to go in (which can be altered with an ICL command).
  826.  
  827.     However, under some multi-tasking OSs it is desirable for multiple Inform
  828.     tasks to work simultaneously without clashes, and this means giving
  829.     the temporary files filenames which include some number uniquely
  830.     identifying the task which is running.  If you want to provide this,
  831.     define INCLUDE_TASK_ID and provide some code...
  832.                                                                            
  833.        #define INCLUDE_TASK_ID                                             
  834.        #ifdef INFORM_FILE                                                  
  835.        static int32 unique_task_id(void)                                   
  836.        {   ...some code returning your task ID...                          
  837.        }                                                                   
  838.        #endif                                                              
  839.  
  840.     /* 6 */
  841.  
  842.     Finally, section 6 is "anything else".  In particular this is where
  843.     DEFAULT_ERROR_FORMAT should be set.  This switches between different
  844.     styles of error message.  (This is not a matter of aesthetics: some
  845.     error-throwback debugging tools are very fussy about what format
  846.     error messages are printed out in.)
  847.  
  848. For example, here is a typical OS definition block:
  849.  
  850. #ifdef UNIX
  851. /* 1 */
  852. #define MACHINE_STRING   "Unix"
  853. /* 2 */
  854. #define CHAR_IS_SIGNED
  855. /* 3 */
  856. #define DEFAULT_MEMORY_SIZE LARGE_SIZE
  857. /* 4 */
  858. #define FN_SEP '/'
  859. #define FILE_EXTENSIONS
  860. /* 5 */
  861. #define Temporary_Directory "/tmp"
  862. #define INCLUDE_TASK_ID
  863. #ifdef INFORM_FILE
  864. static int32 unique_task_id(void)
  865. {   return (int32)getpid();
  866. }
  867. #endif
  868. #endif
  869.                                                                            
  870.  
  871.     2.5   Running Inform in a multi-tasking OS
  872.           ------------------------------------
  873.  
  874. As mentioned above, if Inform is being used in a multi-tasking environment
  875. then temporary file-naming will need a little attention.
  876.  
  877. Another issue is that under some systems the other tasks may all freeze
  878. up while Inform is working, because tasks only voluntarily hand control
  879. back to the OS (allowing it to poll the other tasks and share out the
  880. processor time).  This means that some call to an OS primitive routine
  881. may have to be inserted into Inform somewhere: a good place to do this
  882. is in the routine reached_new_line() of the section "lexer.c".
  883.  
  884.  
  885.     3   The front end
  886.         -------------
  887.  
  888.     3.1   The ICL interpreter
  889.           -------------------
  890.  
  891. Inform's front end is quite simple and there is little to say about it.
  892. Its task is to translate the user's compilation command into five kinds of
  893. ICL variable:
  894.  
  895.     switches, which are on/off flags controlling compilation options;
  896.     switch settings, which are numerical values (between about 1 and 8)
  897.         controlling more finely-controllable compilation options;
  898.     path variables, which hold the text of some directory pathname;
  899.     memory settings, which hold positive numbers (the extent of certain
  900.         memory allocations within Inform);
  901.     the filenames of the source code to read, and the object code to write.
  902.  
  903. See "inform.c" and the memory-setting-parser in "memory.c" for the details.
  904.  
  905.  
  906.     3.2   Fundamental method
  907.           ------------------
  908.  
  909. It is not possible, in almost any compiled language, to make a direct
  910. translation from source to object code "a line at a time": the first time
  911. a line is reached, it often cannot be finally translated until information
  912. is known which cannot yet be known.  (For example, Inform translates an
  913. object's name into a number indicating its position in the final game's
  914. tree of objects.  If the name comes up before the definition of the object
  915. has been seen, Inform cannot know what number to translate the name into.)
  916.  
  917. Inform makes only one pass through the entire source code.  The translation
  918. it makes is (roughly speaking) left blank in places, and these blanks are
  919. filled in at the very end, once the necessary information is available.
  920. This process is called "backpatching": Inform is patching things up behind
  921. itself.
  922.  
  923.  
  924.     4   Lexical analysis
  925.         ----------------
  926.  
  927.     4.1   Aim and structure of the lexer
  928.           ------------------------------
  929.  
  930. The task of the lexical analyser, or "lexer" for short, is to translate the
  931. text it reads into a sequence of "tokens".  The aim is that the rest of the
  932. compiler should work with the tokens and need never look at the original text
  933. again; Inform mainly achieves this aim.
  934.  
  935. Each token represents a sequence of characters, called a "lexeme", which is
  936. indivisible from a syntactic point of view.  For instance, the text
  937.  
  938.     $12+duck.&feathers
  939.  
  940. contains five atomic pieces of syntax:
  941.  
  942.     Token                             Lexeme
  943.  
  944.     <the number 18>                   $12
  945.     <the separator +>                 +
  946.     <symbol number 1>                 duck
  947.     <the separator .&>                .&
  948.     <symbol number 2>                 feathers
  949.  
  950.  
  951. The Inform lexer has three, or perhaps four levels:
  952.  
  953.     Level 1: reading in text, filtering out control characters, etc.
  954.  
  955.     Level 2: a context-free tokeniser
  956.     
  957.     Level 3: a context-dependent process of deciding whether any
  958.              identifier names found are keywords or names made up
  959.              by the programmer
  960.  
  961.  
  962. To make a fairly revolting analogy: when parsing dinner, lexical analysis
  963. is done with the teeth, and syntax analysis with the stomach.  But with
  964. programming languages it is difficult to give a very precise point at
  965. which one ends and the other begins: and in Inform, the "perhaps level 4"
  966. of the lexer occurs when tokens are sorted out more finely in the expression
  967. parser (is this an operator? is it a constant value? is it a variable name?),
  968. which will be documented as part of the syntax analyser in this manual.
  969. At any rate, "lexer.c" and "symbols.c" contain levels 1 to 3 only.
  970.  
  971. For details of some standard algorithms in compiler theory, the account below
  972. and in section 5 gives page references to "ASU": this is Aho, Sethi and
  973. Ullman (1986), "Compilers: Principles, Techniques and Tools", the so-called
  974. "Dragon book".
  975.  
  976. It's called this because the front cover features a knight armoured in
  977. various algorithms confronting a dragon labelled "Complexity of compiler
  978. design": in the case of Inform, though, the dragon might reasonably be
  979. twice as big and labelled "Ignorance of designer who originally chose the
  980. syntax for Inform".  Compiler-making tools like "lex", "yacc" and "bison"
  981. are difficult to apply to this language, since Inform doesn't have a
  982. convenient LALR(1) grammar (more like LALR(4), in fact).  In any case the
  983. lexical and syntax analysers are hand-coded for speed, which is generally
  984. considered to produce code twice as fast as that generated by mechanical
  985. tools like "yacc".
  986.  
  987.  
  988.     4.2   Level 1: lexical blocks and buffered input
  989.           ------------------------------------------
  990.  
  991. The lexer can take input from two sources: from the source code files which
  992. are being compiled, or from a null-terminated string somewhere in the
  993. compiler.  (The latter is used when compiling the "veneer" of run-time
  994. routines.)
  995.  
  996. A "lexical block" is a piece of text which is individually named and
  997. line-counted (so that error messages can indicate where an error has occurred
  998. with reference to the original source).  Each single file of source code
  999. (the original file and each Include file) is a lexical block in its own
  1000. right.  Likewise, if the lexer is reading from an internal string, then
  1001. that string is a lexical block.
  1002.  
  1003. The LexicalBlock structure holds data about the position inside such a block.
  1004. Note that several may be needed at once: if one source file includes another,
  1005. which includes another, then three different LexicalBlocks will contain
  1006. useful information.
  1007.  
  1008. However, information about the files currently being worked from is stored
  1009. in a different structure way, and not in LexicalBlock structures.  For
  1010. efficiency reasons, we can't read characters out of the files one at a time:
  1011. instead we read them in 4096-byte chunks into a buffer.  Note that this
  1012. means that the read-position of a file will be well ahead of the
  1013. read-position of the lexer within it.  It may have been closed before the
  1014. lexer is halfway through its buffer.
  1015.  
  1016. A further complication is that it's natural to use a stack structure to hold
  1017. the files being read from:
  1018.  
  1019.         include file 2          <-- reading from this
  1020.         include file 1          <-- still open but not being read from
  1021.         main source code file   <-- still open but not being read from
  1022.  
  1023. and it is also natural to use a stack structure to hold the LexicalBlocks
  1024. being worked through:
  1025.  
  1026.         LB for include 2
  1027.         LB for include 1
  1028.         LB for main source code file
  1029.  
  1030. Despite the apparent similarity here, we can't combine this into one stack,
  1031. since "include file 2" will have been pushed off the files stack before its
  1032. LB is pushed off the LB stack.  Since further Include directives may occur
  1033. at any point in the current LB, the stacks can be very different.
  1034.  
  1035.  
  1036. Otherwise level 1 is simple and fast.  Note that characters are fed up into
  1037. level 2 through a "pipeline" (see the next section for what this means and
  1038. why), and are also filtered.  Inform can read source files in any plain
  1039. ASCII or any of the ISO 8859 standard ASCII extensions (five variants with
  1040. accented Latin characters, plus Cyrillic, Arabic, Hebrew, Greek).  The
  1041. filtering process removes any character codes undefined in the current
  1042. ISO setting, and normalises new-line and spacing characters:
  1043.  
  1044.       00                         remains 0 (meaning "end of file")
  1045.       TAB                        becomes SPACE
  1046.       0d                         becomes 0a, i.e., '\n'
  1047.       other control characters become '?'
  1048.       7f                         becomes '?'
  1049.       80 to 9f                   become '?'
  1050.       a0                         (ISO "non-breaking space") becomes SPACE
  1051.       ad                         (ISO "soft hyphen") becomes '-'
  1052.       any character undefined in ISO between a0 and ff is mapped to '?'
  1053.  
  1054. (Here "ISO" means "the current ISO setting", which can be 0, meaning
  1055. plain ASCII only: in this mode any character value of 80 to ff will
  1056. be filtered to '?'.)
  1057.  
  1058. The filtering ensures that (i) no error message can contain an unprintable
  1059. character and (ii) the user cannot type a character outside a standard
  1060. ISO set and which might work on one platform but not on another.
  1061.  
  1062. Note that the 0 character is only fed upwards into level 2 when the entire
  1063. lexical source has run out: that is, all the source files are exhausted,
  1064. or else the string being analysed has run out.
  1065.  
  1066.  
  1067.     4.3   Level 2: breaking text into lexemes
  1068.           -----------------------------------
  1069.  
  1070. The input to level 2, then, is a stream of characters: and its output is a
  1071. stream of tokens, each of which represents a sequence of characters called a
  1072. "lexeme".
  1073.  
  1074. Some definitions of terms used in the Inform source code.  There is a fixed
  1075. set of "separators", all of them sequences of 1 to 3 mainly non-alphabetic
  1076. characters:
  1077.  
  1078.     ->     -->    --     -     ++    +    *    /    %
  1079.     ||     |      &&     &     ~~
  1080.     ~=     ~      ==     =     >=    >
  1081.     <=     <      (      )     ,
  1082.     .&     .#     ..&    ..#   ..    .
  1083.     ::     :      @      ;     [     ]    {    }
  1084.     $      ?~     ?
  1085.     #a$    #n$    #r$    #w$   ##    #
  1086.  
  1087. An "identifier" is a sequence of one or more characters from the set:
  1088.  
  1089.     A B C D ... Z a b c ... z 0 1 2 3 4 5 6 7 8 9 _
  1090.  
  1091. which does not begin with 0 to 9.  The lexer makes the longest lexeme it
  1092. possibly can for any particular token, so the next character after any
  1093. identifier will not be one of the set above.
  1094.  
  1095. The lexemes representing numbers are:
  1096.  
  1097.     (a) one or more chars from the set 0 1 2 3 4 5 6 7 8 9
  1098.     (b) $ followed by one or more chars from 0 1 2 3 4 5 6 7 8 9 A B C D E F
  1099.         (hexadecimal numbers)
  1100.     (b) $$ followed by one or more chars from 0 1
  1101.         (binary numbers)
  1102.  
  1103. Note that "-67" is not a lexeme for a single token: it is broken into two
  1104. lexemes, "-" and "67".
  1105.  
  1106. A ", followed by any number of characters and then another ", is a single
  1107. lexeme.  Similarly for '.
  1108.  
  1109. Finally, as a special case, the six separators
  1110.  
  1111.     #a$    #n$    #r$    #w$   ##    #
  1112.  
  1113. are expected to be followed by an identifier.  For example, "##Take" is
  1114. a single lexeme, and is not divided into "##" and "Take".  (Except that
  1115. #n$ can be followed by any character, so that e.g. #n$1 is a single token,
  1116. representing "the new dictionary word '1'" in the language.)
  1117.  
  1118. To sum up, the lexical analyser expects legal source code to contain:
  1119.  
  1120.     "comments": sequences beginning with a ! character and ending with a
  1121.     new-line or the end of the file or string containing it
  1122.  
  1123.     any of the lexemes above
  1124.  
  1125.     "white space", that is, characters in the set
  1126.         space  tab  new-line
  1127.  
  1128.  
  1129. When breaking down text into lexemes (and throwing away the white space
  1130. and comments), the lexer needs 3 characters of look-ahead.  That is, it can
  1131. decide definitely what lexeme character N belongs to provided that it knows
  1132. what characters N+1, N+2 and N+3 are.  (The figure 3 occurs because that's
  1133. the worst case arising: deciding whether character N is the start of a
  1134. separator in the form "#a$" followed by an identifier character.)
  1135.  
  1136. Because of this, level 1 maintains a "pipeline" of four variables to hold the
  1137. current character and the next three on the way.  By looking ahead at the
  1138. pipeline as needed, level 2 decides what to do with the current character and
  1139. then advances one character: the three waiting in the pipeline shuffle up and
  1140. a new character is read into the last place in the pipeline.  The advantage
  1141. of maintaining a pipeline is that the lexer never needs to undo any decisions
  1142. and go backward through the text.
  1143.  
  1144.  
  1145. One token is output for each lexeme found, and when the lexer runs out of
  1146. input altogether (when all the source files are finished, or when the string
  1147. being analysed has run out) a special token, called "end of file", is output. 
  1148. Thus the lexer's output is a sequence of tokens from the list:
  1149.  
  1150.     numbers
  1151.     strings in " quotes
  1152.     strings in ' quotes
  1153.     separators
  1154.     identifiers
  1155.     end-of-file
  1156.  
  1157. As will be seen in the next section, identifiers are analysed further before
  1158. being passed out of the lexer.
  1159.  
  1160. Except for the problem of deciding what an identifier means, the lexer is
  1161. "context-free": it needs to know nothing about the syntax of the Inform
  1162. language, what kind of code it is currently analysing, etc.  There is a
  1163. standard state-machine algorithm for writing such a lexer: see ASU, p. 98.
  1164. The tricky part is to efficiently store a transition table for the states
  1165. involved, which will be neither so small that slow code is required to
  1166. read it, nor so large that it takes up an unacceptable amount of memory.
  1167. Here the "tokeniser_grid" stores most of a transition table: this is an
  1168. algorithm originally suggested to me by Dilip Sequeira, similar to that used
  1169. by S. C. Johnson's "yacc" lexical analyser.
  1170.  
  1171.  
  1172.     4.4   Representation of tokens
  1173.           ------------------------
  1174.  
  1175. Tokens are internally stored as quadruples:
  1176.  
  1177.     typedef struct token_data_s
  1178.     {   char *text;
  1179.         int value;
  1180.         int type;
  1181.         int marker;
  1182.     } token_data;
  1183.  
  1184. though the lexer is not responsible for writing "marker" values, which are
  1185. the concern of the syntax analyser.  The "type" identifies which kind of
  1186. token it is (this value must be one of the *_TT set #define'd in "header.h"):
  1187. for example, DQ_TT means "a double-quoted string".  The "value" is a
  1188. number whose meaning depends on the type.  For example, in the case of
  1189. type DQ_TT, the number has no meaning and is not used; in the case of type
  1190. SEP_TT (for "separator"), the number gives the index in the above table
  1191. of possible separators, thus identifying which separator it is.
  1192.  
  1193. "text" is a pointer to a null-terminated string containing the lexeme. There
  1194. are two reasons this is needed: firstly, so that comprehensible error
  1195. messages can be printed out from higher up in the compiler, and secondly
  1196. because in the case of DQ_TT and SQ_TT the text may need to be compiled
  1197. into Z-text format and added to the static strings area, to the Z-code area
  1198. or to the dictionary.  The decision on whether the string should be compiled
  1199. and if so, what to, cannot be taken until code generation time.
  1200.  
  1201. Unfortunately code generation time may not be for a while, and this raises a
  1202. problem: we clearly need to keep lexeme text in memory for a while, but it
  1203. would be very costly on memory to keep the text of every token in memory
  1204. permanently.  When is it safe for the lexer to throw a lexeme away?
  1205.  
  1206. One solution would be for a formal system by which the code generator
  1207. explicitly deallocated the space, but this is too bureaucratic and too risky
  1208. (suppose we miss 0.1% of these? Memory will slowly clog up and begin to cause
  1209. odd errors on large compilation runs).  Instead, the lexer simply writes its
  1210. text cyclically into a large buffer.  Code generation almost always takes
  1211. place before the lexer has got any more than 100 or so bytes of text ahead;
  1212. since the buffer is a good 10K long, there is a generous safety margin.
  1213.  
  1214.  
  1215.     4.5   Level 3: identifying identifiers
  1216.           --------------------------------
  1217.  
  1218. A "keyword" is an identifier which has a meaning understood by the Inform
  1219. compiler: for example the lexeme
  1220.  
  1221.     while
  1222.  
  1223. is understood (in some contexts) to refer to the "while" statement, rather
  1224. than being a name coined by the programmer for some variable or object.
  1225.  
  1226. In most small languages such a lexeme would always be a keyword and never a
  1227. name.  (This is the concept of "reserved word": a word reserved for the use
  1228. of the compiler, forbidden as a name.) For example, the fairly-large language
  1229. C++ has 48 such keywords.
  1230.  
  1231. Inform is unable to reserve keywords (that is, forbid their use as names) for
  1232. two reasons: firstly, because there are 281 of the damn things (and 116 of
  1233. them are only significant in lines of assembly language: why forbid the use
  1234. of these to non-assembly-language programmers?), and secondly because it is
  1235. important to the language that some keywords definitely should be the same as
  1236. some object names.  "Class" is both a keyword meaning "the class-making
  1237. directive" and a name meaning "the object representing the class of all
  1238. classes".
  1239.  
  1240. So the decision "is this identifier intended to be a keyword or intended
  1241. to be the name of something?" relies on the context.  What the lexer does
  1242. is to divide the 281 keywords into twelve groups.  The syntax analyser
  1243. switches these groups on or off as it finds its way through the program.
  1244. For example, the group "opcode_names" is only enabled (i.e., switched on)
  1245. after an @ character has been read at the beginning of a statement.
  1246.  
  1247. A complication is that case is sensitive for some of these groups and not
  1248. others.  For example, "IFDEF and "Ifdef" both match the directive name
  1249. "ifdef", but "WHILE" and "While" do not match the statement name "while".
  1250. The rules in fact are:
  1251.  
  1252.          When matching...                        Example          Sensitive?
  1253.  
  1254.          Language keywords:
  1255.              directive names                     Class            No
  1256.              keywords used within directives     with             Yes
  1257.              statement names                     while            Yes
  1258.              keywords used within statements     else             Yes
  1259.              condition names                     hasnt            Yes
  1260.              built-in function names             random           Yes
  1261.              built-in constant names             #code_offset     Yes
  1262.  
  1263.          Assembly language keywords:
  1264.              opcode names                        put_prop         Yes
  1265.              customised opcode names             @"1OP:4S"        Yes
  1266.              the stack pointer name              sp               Yes
  1267.  
  1268.          Names for variables, objects, etc.      lantern          No
  1269.          Names for actions                       Take             No
  1270.  
  1271. Moreover, in contexts where local variables are allowed, they take
  1272. precedence over the rest.  (For example, you could define a local variable
  1273. called "random", and for the duration of that routine the word "random"
  1274. would never be recognised as the keyword for the system function random().)
  1275.  
  1276. Each keyword group has its own token type.  The token value for a keyword
  1277. token is the index within the group: see "header.h" for #define's for
  1278. all of these indices.
  1279.  
  1280. Finally, there are times when the syntax analyser just wants the raw text
  1281. of an identifier, and doesn't want it identified (for efficiency reasons:
  1282. this prevents it from being entered into the symbols table).  If the
  1283. dont_enter_into_symbols_table flag is set, the lexer simply returns a
  1284. token of type DQ_TT as though the name had been found in double-quotes.
  1285.  
  1286.  
  1287.     4.6   Hash-coding and comparing names
  1288.           -------------------------------
  1289.  
  1290. It would be computationally very expensive indeed to decide whether string X
  1291. is a keyword or not by carrying out direct string comparisons with all 281
  1292. keywords.  Instead, hash-coding is used.  The idea is to perform a fast
  1293. operation on X whose result is some number from, say, 1 to 100: this is the
  1294. hash code of X.  If X is the same string as K, then K must have the same hash
  1295. code.  So we organise the keywords into 100 different groups, the group with
  1296. hash code 1, with hash code 2, etc.: then if h is the hash code of X, we only
  1297. need to compare X with the keywords in group h.
  1298.  
  1299. For this to be any use, the operation performed has to be chosen so that
  1300. the keywords are sorted out into groups with about equal numbers in each.
  1301. Many sensible "hash functions" are known (see ASU, p. 437 for experimental
  1302. performance data).  Inform's choice is simple but effective: it uses
  1303. multiplication rather than bit-shifting, but then on modern CPUs
  1304. multiplication is not very expensive.  The algorithm is what ASU would
  1305. call "X 30011":
  1306.  
  1307.   extern int hash_code_from_string(char *p)
  1308.   {   unsigned int32 hashcode=0;
  1309.       for (; *p; p++) hashcode=hashcode*30011 + case_conversion_grid[*p];
  1310.       return (int) (hashcode % HASH_TAB_SIZE);
  1311.   }
  1312.  
  1313. where "hashcode" is meant to overflow repeatedly.  Note that 30011 is a prime
  1314. number.  (case_conversion_grid[*p] is just a fast way to convert all lower
  1315. case letters to upper case ones, since we want case to be insignificant when
  1316. calculating hash codes.)  It doesn't matter if this algorithm behaves
  1317. differently on different machines (depending on how the CPU copes with
  1318. overflows): all that matters is it delivers a reasonable spread of hash
  1319. values.
  1320.  
  1321. The hash code range is 0 to HASH_TAB_SIZE-1: this is a memory setting
  1322. which by default is 512.  Reducing this by any substantial amount causes a
  1323. significant slowing down of Inform.
  1324.  
  1325.  
  1326.     4.7   The symbols table
  1327.           -----------------
  1328.  
  1329. If an identifier, in context, isn't a keyword then it is called a "symbol":
  1330. this basically means "a name for something created by the programmer"
  1331. (except that Inform creates a few symbols automatically as well).
  1332.  
  1333. The section "symbols.c" keeps a table of all the symbols which have turned
  1334. up so far.  (It often picks up a few extraneous names of keywords, too,
  1335. when the lexer has been looking ahead in the wrong context: but this doesn't
  1336. matter and it's faster to tolerate the slight waste of memory.)
  1337.  
  1338. The symbols table is organised into HASH_TAB_SIZE-1 linked lists, each of
  1339. which is kept in alphabetical order.  A single operation is provided for
  1340. searching it: symbol_index(), which works out the hash code of the string S
  1341. supplied (unless it's already known, in which case it need not work it out
  1342. again) and looks through the linked list for that hash code until the
  1343. first letter matches.  (Thus, the only full string comparisons made are
  1344. between S and those strings in the table which have the same hash code
  1345. and the same initial letter.)  If S is not present, it is inserted into
  1346. the table.
  1347.  
  1348. In addition to its text, each symbol in the table has four pieces of data
  1349. attached: its type, its value, the line on which it was assigned and its
  1350. flags.  The symbol with index i has:
  1351.  
  1352.         symbs[i]        text             
  1353.         stypes[i]       type             char
  1354.         svals[i]        value            int32
  1355.         sflags[i]       flags word       int
  1356.         slines[i]       line number      int32
  1357.  
  1358. (It would be more elegant to store this as an array of structures, but
  1359. the symbols table is a major consumer of memory, so we can't afford to let
  1360. lazy compilers waste it by aligning the fields of such a structure
  1361. at 4 byte intervals.  Hence, five separate arrays.)
  1362.  
  1363. Types and values are assigned by the syntax analyser: the type indicates
  1364. what kind of thing the symbol is a name of (a routine, a label, an object,
  1365. etc.), and must always be one of the #define names *_T (see "header.h").  The
  1366. value holds some number indicating which particular thing the symbol is a
  1367. name of (a routine address, an object number, etc.).
  1368.  
  1369. The line number is set when the symbol is first used, and then reset when it
  1370. is first assigned a value (if ever).  The information is stored as
  1371.  
  1372.     file-number*0x10000 + line-number
  1373.  
  1374. where file-number is an index into the InputFiles array maintained by
  1375. "files.c".
  1376.  
  1377. The flags word holds (presently) 15 different flags, for different properties
  1378. that the symbol name can have.  These flags have #define names in the form
  1379. *_SFLAG.
  1380.  
  1381. The token for a symbol has type SYMBOL_TT and value equal to the index i of
  1382. the symbol within the symbols table.
  1383.  
  1384.  
  1385.     4.8   Token lookahead: the circle
  1386.           ---------------------------
  1387.  
  1388. The output of the lexer is sent, one token at a time, when the syntax
  1389. analyser calls get_next_token().
  1390.  
  1391. The syntax analyser is a predictive parser which makes mistakes and has to
  1392. backtrack (that is, it reads in token X, guesses that it might be looking at
  1393. XY and reads the next token to see... but reads a Z instead, and has to go
  1394. back to X and try a different theory).  So the syntax analyser needs to be
  1395. able to go backwards, as well as forwards, in the stream of tokens.
  1396.  
  1397. This means that the lexer needs to remember its last N tokens, where N is
  1398. the maximum number of backward steps the syntax analyser ever takes in one
  1399. go.  The number N is the amount of "lookahead", since one could also think
  1400. of it as the maximum tokens one needs to look ahead of the current position
  1401. to be sure of what is happening.
  1402.  
  1403. These tokens are therefore stored in a "circle" of N+1 tokens: when
  1404. get_next_token() is called, the lexer works out the next token, writes
  1405. it into the circle and moves on one place clockwise; when put_token_back() is
  1406. called, the lexer moves back one place anticlockwise, so that the next
  1407. get_next_token() will send back the token in that position rather than work
  1408. out a new one.
  1409.  
  1410. However, the interpretation of identifiers as keyword or symbol depends on
  1411. the current context, and this may have changed since the token was first
  1412. calculated.  Therefore a numerical representation of the context is stored
  1413. in the circle too, so that if this has changed and if the token is an
  1414. identifier then it is re-identified under the context which now prevails.
  1415.  
  1416.  
  1417.     4.9   Summary of the lexer's output
  1418.           -----------------------------
  1419.  
  1420. To summarise, the lexer converts source text to a stream of tokens of types
  1421. as follows:
  1422.  
  1423.     --------------------------------------------------------------------------
  1424.     Type                  Lexeme                    Value
  1425.     --------------------------------------------------------------------------
  1426.     NUMBER_TT             literal number in         the number
  1427.                           decimal, hex or binary
  1428.     DQ_TT                 string extracted from     (none)
  1429.                           double-quotes
  1430.                           (or identifier name:
  1431.                           see above for when)
  1432.     SQ_TT                 string extracted from     (none)
  1433.                           single-quotes
  1434.     SEP_TT                separator                 a #define'd *_SEP value
  1435.     EOF_TT                (end of source)           (none)
  1436.  
  1437.     SYMBOL_TT             identifier assumed        index in the symbols
  1438.                             to be a name              table
  1439.  
  1440.     LOCAL_VARIABLE_TT     local variable name       1 to 15, its Z-machine
  1441.                                                       variable number
  1442.     STATEMENT_TT          statement name            a #defined *_CODE value
  1443.     SEGMENT_MARKER_TT     with/has/class etc.       a #defined *_SEGMENT value
  1444.     DIRECTIVE_TT          directive name            a #defined *_CODE value
  1445.     CND_TT                named conditional         a #defined *_COND value
  1446.     SYSFUN_TT             built-in function         a #defined *_SYSFUN value
  1447.     OPCODE_NAME_TT        opcode name               a #defined *_zc value
  1448.                                                       (i.e., an internal
  1449.                                                       opcode number)
  1450.     MISC_KEYWORD_TT       keyword like "char" used  a #defined *_MK value
  1451.                           in statement syntax       
  1452.     DIR_KEYWORD_TT        keyword like "meta" used  a #defined *_DK value
  1453.                           in directive syntax       
  1454.     TRACE_KEYWORD_TT      keyword used in syntax    a #defined *_TK value
  1455.                           of "trace" directive
  1456.     SYSTEM_CONSTANT_TT    system #constant name     a #defined *_SC value
  1457.     --------------------------------------------------------------------------
  1458.  
  1459. Note that other token types do exist, but are set in "level 4": i.e., within
  1460. the expression parser.
  1461.  
  1462.  
  1463.     5   Syntax analysis
  1464.         ---------------
  1465.  
  1466.     5.1   Aim and structure of the syntax analyser
  1467.           ----------------------------------------
  1468.  
  1469. The syntax analyser is the heart of Inform, and contains within it the
  1470. specification of the language.
  1471.  
  1472. Inform code fundamentally consists of directives, which are instructions to
  1473. the compiler to do something, and routines containing statements, which are
  1474. lines of code to be executed at run-time.
  1475.  
  1476. The syntax analyser takes as input the stream of tokens from the lexer.  Some
  1477. of these are interpreted as directives and acted on immediately.  Others
  1478. are realised to be statements and compiled; we can regard the output of the
  1479. compiling part of the analyser as being a stream of Z-machine assembly
  1480. language, passed down into "asm.c".
  1481.  
  1482. In most modern compilers, the syntax analyser would convert the token
  1483. stream into a "parse tree" expressing the structure of the input: something
  1484. along the lines of
  1485.  
  1486.                    routine
  1487.                   /      \
  1488.               statement   statement
  1489.                  |           |
  1490.                 "if"         ...etc., etc.
  1491.                /    \
  1492.           condition  statement
  1493.               |         |
  1494.             "=="     "print"
  1495.             /   \       |
  1496.           "x"   "0"  "Good heavens!"
  1497.  
  1498. This is aesthetic, and makes possible many optimisations (such as elimination
  1499. of common sub-expressions), since the compiler is able to see the whole
  1500. structure before beginning to compile it.  But it uses up a fair amount of
  1501. memory (admittedly, most compilers only keep the tree for the current
  1502. routine, not the tree for the entire program); and a lot of speed, as the
  1503. tree is trawled through again and again.
  1504.  
  1505. Characteristically, Inform instead uses an algorithm which is about 40 years
  1506. old (see ASU, p.181 et seq).  It doesn't generate a parse tree for whole
  1507. routines, though it does do so for expressions, assignments and conditions:
  1508. for example, it would have built the little tree:
  1509.  
  1510.             "=="
  1511.             /   \
  1512.           "x"   "0"
  1513.  
  1514. For higher level-parsing, it works "top-down", making recursive function
  1515. calls which mimic a depth-first traversal of the tree drawn above.  That is,
  1516.  
  1517.     routine()
  1518.         calls statement()
  1519.             which reads the token "if"
  1520.             and calls condition()
  1521.                 which works out the expression "x == 0"
  1522.             and compiles some code to perform this test and
  1523.             then to skip the next instruction if it's false
  1524.             and calls statement()
  1525.                 which reads the token "print"
  1526.                 and then the token "Good heavens!"
  1527.                 and compiles some code to print this
  1528.         and routine() next calls statement()
  1529.             which reads... etc., etc.
  1530.  
  1531. Although we are only able to go through the tree once, it's a quick and
  1532. efficient trip, effectively using the C run-time stack to hold the parse
  1533. tree structure.  The result is also a rather legible piece of source
  1534. code (as compared, for example, with the output from "yacc").  (The main
  1535. reason we can escape from having to make parse trees is that our target
  1536. machine, the Z-machine, has an architecture making register allocation
  1537. unnecessary: the variables are the registers, and there's no space or
  1538. time penalty for use of the stack.)
  1539.  
  1540. The syntax analyser begins with parse_program() in the section "syntax.c".
  1541. Because its structure is embodied in the source code, there is relatively
  1542. little to say about it except to refer the reader to that: and to the
  1543. the table in section 1.1 above.
  1544.  
  1545.  
  1546.     5.2   Predictive parsing
  1547.           ------------------
  1548.  
  1549. Note that tokens can be read from many different places, and code can be
  1550. passed out from many different places: whereas the lexer and the assembler
  1551. each have a single channel of input and output.
  1552.  
  1553. As a typical example of the syntax analyser working as a "predictive parser"
  1554. and having to "backtrack", consider how parse_action() begins to parse through
  1555. action statements like
  1556.  
  1557.     <Take fishknife>;          tokenised as    <
  1558.                                                symbol "Take"
  1559.                                                symbol "fishknife"
  1560.                                                >
  1561.  
  1562. When it's called, the first token, "<" has already been read (this is how
  1563. parse_statement() knew to call parse_action() in the first place).
  1564.  
  1565. What it does is:
  1566.  
  1567.     "Predict" that it's going to be a << ... >> statement
  1568.     Ask the lexer for a token, expecting it to be another "<"
  1569.     Discover that, unfortunately, it's a symbol, so the prediction was wrong
  1570.     Backtrack to the point where it made the wrong prediction
  1571.         (this actually only means giving the token "Take" back into
  1572.         the lexer again)
  1573.     Now predict the next possibility, that it's a < ... > statement
  1574.     Ask the lexer for a token, expecting it to be a symbol name
  1575.     Discover that this time it is ("Take"), so the prediction was correct
  1576.     ... and so on.
  1577.  
  1578. The code to do this is more like:
  1579.  
  1580.     get_next_token();
  1581.     if (token == "<") return parse_double_angle_action();
  1582.     put_token_back();
  1583.     return parse_single_angle_action();
  1584.  
  1585. (The actual code doesn't make these inefficient function calls, and token
  1586. comparison is a bit fiddlier, but this is the idea.)
  1587.  
  1588.  
  1589. Clearly, the longer such a prediction goes on before it is found to be
  1590. wrong, the more tokens which the lexer has to take back again.  The syntax
  1591. of the language determines this number, N: for many languages N = 1 (because
  1592. they've been designed that way) but for Inform N = 5 (because it was defined
  1593. by an ignorant oaf).  (Though, as will appear in the next section, it would
  1594. be possible to reduce this by implementing the grammar differently: and
  1595. there are compensations, such as the relative conciseness of Inform code.)
  1596.  
  1597.  
  1598.  
  1599.     5.3   The context-free grammar
  1600.           ------------------------
  1601.  
  1602. Here are the productions which the top-down syntax analyser implements.
  1603. (Most of the major ones are handled by routines.)
  1604.  
  1605. "void_expression", "constant", "condition" and "quantity" are left undefined:
  1606. these are handled by the expression parser according to an operator-precedence
  1607. grammar.  "vcondition" is a condition whose first token is a VARIABLENAME.
  1608. Symbols are represented in capitals; NEWNAME means one not so far assigned
  1609. a value, while CLASSNAME, etc., mean an existing symbol of the given type.
  1610. Obsolete features which are still supported are omitted.
  1611.  
  1612. Details of conditional compilation are abbreviated heavily: the notation
  1613. PROGRAM means "anything at all until the right directive keyword comes up
  1614. at the same #if... level".
  1615.  
  1616.   =========================================================================
  1617.   program      ->    directive ; program
  1618.  
  1619.   directive    ->    [ NEWNAME routine
  1620.                      "Abbreviate" strings
  1621.                      "Array" NEWNAME arraytype array
  1622.                      "Attribute" NEWNAME
  1623.                      "Attribute" NEWNAME "alias" ATTRIBUTENAME
  1624.                      "Class" NEWNAME objbody
  1625.                      "Class" NEWNAME ( constant ) objbody
  1626.                      "Constant" NEWNAME
  1627.                      "Constant" NEWNAME constant
  1628.                      "Constant" NEWNAME = constant
  1629.                      "Default" NEWNAME constant
  1630.                      "End"
  1631.                      "Extend" extension
  1632.                      "Fake_action" NEWNAME
  1633.                      "Global" NEWNAME
  1634.                      "Global" NEWNAME = constant
  1635.                      "Ifdef" NAME condcomp
  1636.                      "Ifndef" NAME condcomp
  1637.                      "Iftrue" constant condcomp
  1638.                      "Iffalse" constant condcomp
  1639.                      "Ifv3" constant condcomp
  1640.                      "Ifv5" constant condcomp
  1641.                      "Import" manifest
  1642.                      "Include" STRING
  1643.                      "Link" STRING
  1644.                      "Lowstring" NEWNAME STRING
  1645.                      "Message" diagnostic
  1646.                      "Nearby" objhead objbody
  1647.                      "Object" arrows objhead objbody
  1648.                      "Property" NEWNAME propdef
  1649.                      "Release" quantity
  1650.                      "Replace" ROUTINENAME
  1651.                      "Serial" STRING
  1652.                      "Statusline" "score"
  1653.                      "Statusline" "time"
  1654.                      "Stub" NAME quantity
  1655.                      "Switches" TEXT                <---- An unquoted string
  1656.                      "System_file"
  1657.                      "Trace" trace
  1658.                      "Verb" verb
  1659.                      "Zcharacter" zchar
  1660.                      CLASSNAME arrows objhead objbody
  1661.  
  1662.   condcomp     ->    ; PROGRAM ; "Endif"
  1663.                      ; PROGRAM ; "Ifnot" ; PROGRAM ; "Endif"
  1664.  
  1665.   manifest     ->    import "," manifest
  1666.                      import
  1667.   import       ->    "global" NEWNAME
  1668.  
  1669.   diagnostic   ->    STRING
  1670.                      "error" STRING
  1671.                      "fatalerror" STRING
  1672.                      "warning" STRING
  1673.  
  1674.   propdef      ->    propdefault
  1675.                      "additive" propdefault
  1676.   propdefault  ->    <empty>
  1677.                      quantity
  1678.   =========================================================================
  1679.   trace        ->    t_section t_level                    Tracing
  1680.   t_section    ->    <empty>
  1681.                      "objects"
  1682.                      "symbols"
  1683.                      "verbs"
  1684.                      "assembly"
  1685.                      "expressions"
  1686.                      "lines"
  1687.   t_level      ->    <empty>
  1688.                      "on"
  1689.                      "off"
  1690.                      quantity
  1691.   =========================================================================
  1692.   zchar        ->    char_spec                            Character set
  1693.                      STRING STRING STRING
  1694.                      "table" char_specs
  1695.                      "table" "+" char_specs
  1696.   char_specs   ->    char_spec char_specs
  1697.                      char_spec
  1698.   char_spec    ->    LITERAL_CHARACTER
  1699.   =========================================================================
  1700.   arrows       ->    "->" arrows                          Object definition
  1701.                      <empty>
  1702.   objhead      ->    <empty>
  1703.                      NEWNAME
  1704.                      STRING
  1705.                      NEWNAME STRING
  1706.                      NEWNAME OBJECTNAME
  1707.                      STRING OBJECTNAME
  1708.                      NEWNAME STRING OBJECTNAME
  1709.   objbody      ->    segment objbody
  1710.                      segment "," objbody
  1711.   segment      ->    "class" class_s
  1712.                      "with" with_s
  1713.                      "private" with_s
  1714.                      "has" has_s
  1715.   class_s      ->    CLASSNAME class_s
  1716.   with_s       ->    PROPERTYNAME property
  1717.                      PROPERTYNAME property "," with_s
  1718.   has_s        ->    attributes
  1719.   property     ->    <empty>
  1720.                      [ routine
  1721.                      arrayvals
  1722.   =========================================================================
  1723.   arraytype    ->    ->                                   Arrays
  1724.                      -->
  1725.                      "string"
  1726.                      "table"
  1727.   array        ->    constant
  1728.                      STRING
  1729.                      arrayvals
  1730.                      [ manyvals ]
  1731.   manyvals     ->    constant manyvals
  1732.                      constant ; manyvals
  1733.   arrayvals    ->    constant arrayvals
  1734.   =========================================================================
  1735.   extension    ->    "only" strings priority grammar      Grammar
  1736.                      STRING priority grammar
  1737.   priority     ->    <empty>
  1738.                      "replace"
  1739.                      "first"
  1740.                      "last"
  1741.  
  1742.   verb         ->    strings v_setting
  1743.                      "meta" strings v_setting
  1744.   v_setting    ->    = STRING
  1745.                      grammar
  1746.  
  1747.   grammar      ->    g_line grammar
  1748.   g_line       ->    * tokens -> g_action
  1749.   g_action     ->    ACTIONNAME
  1750.                      ACTIONNAME "reverse"
  1751.  
  1752.   tokens       ->    g_token tokens
  1753.   g_token      ->    preposition
  1754.                      "noun"
  1755.                      "held"
  1756.                      "multi"
  1757.                      "multiheld"
  1758.                      "multiexcept"
  1759.                      "multiinside"
  1760.                      "creature"
  1761.                      "special"
  1762.                      "number"
  1763.                      "topic"
  1764.                      "noun" = ROUTINENAME
  1765.                      "scope" = ROUTINENAME
  1766.                      ATTRIBUTENAME
  1767.                      ROUTINENAME
  1768.  
  1769.   preposition  ->    DICTIONARYWORD
  1770.                      DICTIONARYWORD / preposition
  1771.  
  1772.   strings      ->    STRING strings
  1773.  
  1774.   attributes   ->    attribute attributes
  1775.   attribute    ->    ATTRIBUTENAME
  1776.                      ~ ATTRIBUTENAME
  1777.   =========================================================================
  1778.   routine      ->    * locals ; body ]                    Everything below
  1779.                      locals ; body ]                      here is code to
  1780.   locals       ->    NAME locals                          compile
  1781.                      <empty>
  1782.  
  1783.   body         ->    action_case : body
  1784.                      "default" : body
  1785.                      statement body
  1786.   action_case  ->    ACTIONNAME
  1787.                      ACTIONNAME , action_case
  1788.  
  1789.   block        ->    ;
  1790.                      statement ;
  1791.                      { states }
  1792.                      { states . NEWNAME ; }
  1793.   states       ->    statement states;
  1794.  
  1795.   s_block      ->    { s_states }
  1796.                      { s_states . NEWNAME ; }
  1797.   s_states     ->    case : s_states
  1798.                      "default" : s_states
  1799.                      statement s_states
  1800.   case         ->    range :
  1801.                      range , case
  1802.   range        ->    constant
  1803.                      constant "to" constant
  1804.   =========================================================================
  1805.   statement    ->    . NEWNAME ; statement
  1806.                      "@" assembly ;
  1807.                      "<" action ">" ;
  1808.                      "<<" action ">>" ;
  1809.                      indiv_state
  1810.                      STRING
  1811.                      void_expression
  1812.  
  1813.   action       ->    ACTIONNAME
  1814.                      ACTIONNAME quantity
  1815.                      ACTIONNAME quantity quantity
  1816.  
  1817.   assembly     ->    opcode operands options
  1818.   opcode       ->    OPCODENAME
  1819.                      STRING                          <--- customised opcode
  1820.   operands     ->    operand operands                     descriptions are
  1821.   operand      ->    constant                             not parsed by the
  1822.                      VARIABLENAME                         syntax analyser
  1823.                      sp
  1824.   options      ->    ? branch
  1825.                      -> store
  1826.                      -> store ? branch
  1827.   store        ->    VARIABLENAME
  1828.                      sp
  1829.   branch       ->    LABELNAME
  1830.                      ~ LABELNAME
  1831.   =========================================================================
  1832.   indiv_state  ->    "box" strings ;
  1833.                      "break" ;
  1834.                      "continue" ;
  1835.                      "do" eblock "until" ( condition ) ;
  1836.                      "font" "on" ;
  1837.                      "font" "off" ;
  1838.                      "for" ( for1 : for2 : for3 ) block ;
  1839.                      "give" quantity attributes ;
  1840.                      "if" ( condition ) block
  1841.                      "if" ( condition ) block "else" block
  1842.                      "inversion" ;
  1843.                      "jump" LABELNAME ;
  1844.                      "move" quantity "to" quantity ;
  1845.                      "new_line" ;
  1846.                      "objectloop" ( ospec ) block ;
  1847.                      "print" printlist ;
  1848.                      "print_ret" printlist ;
  1849.                      "quit" ;
  1850.                      "read" quantity quantity ;
  1851.                      "read" quantity quantity ROUTINENAME ;
  1852.                      "remove" quantity ;
  1853.                      "restore" LABELNAME ;
  1854.                      "return" ;
  1855.                      "return" quantity ;
  1856.                      "rtrue" ;
  1857.                      "rfalse" ;
  1858.                      "save" LABELNAME ;
  1859.                      "spaces" quantity ;
  1860.                      "string" quantity STRING ;
  1861.                      "style" textstyle ;
  1862.                      "switch" ( quantity ) s_block
  1863.                      "while" ( condition ) block
  1864.   for1         ->    void_expression
  1865.                      <empty>
  1866.   for2         ->    condition
  1867.                      <empty>
  1868.   for3         ->    void_expression
  1869.                      <empty>
  1870.   ospec        ->    VARIABLENAME
  1871.                      VARIABLENAME "in" quantity
  1872.                      VARIABLENAME "near" quantity
  1873.                      VARIABLENAME "from" quantity
  1874.                      vcondition
  1875.   printlist    ->    printitem , printlist
  1876.                      printitem
  1877.   printitem    ->    STRING
  1878.                      quantity
  1879.                      ( form ) quantity
  1880.   form         ->    ROUTINENAME
  1881.                      "number"
  1882.                      "char"
  1883.                      "address"
  1884.                      "string"
  1885.                      "The"
  1886.                      "the"
  1887.                      "a"
  1888.                      "an"
  1889.                      "name"
  1890.                      "object"
  1891.                      "identifier"               
  1892.   textstyle    ->    "roman"
  1893.                      "reverse"
  1894.                      "bold"
  1895.                      "underline"
  1896.                      "fixed"
  1897.   =========================================================================
  1898.  
  1899. A few critical comments on the above.
  1900.  
  1901. From this grammar it's possible to work out N, the maximum look-ahead needed
  1902. to distinguish which production is being used in the source code.  The worst
  1903. cases are:
  1904.  
  1905.    (a) distinguishing productions (1) and (2) in
  1906.  
  1907.        ospec     -> VARIABLENAME
  1908.                     VARIABLENAME "in" quantity     (1)
  1909.                     VARIABLENAME "near" quantity
  1910.                     VARIABLENAME "from" quantity
  1911.                     vcondition                     (2)
  1912.      
  1913.        which requires N = 5; these two productions need to be distinguished
  1914.        between because
  1915.  
  1916.        objectloop ( a in b )
  1917.        objectloop ( a in b ... )
  1918.  
  1919.        (the second containing a compound condition) compile quite different
  1920.        code: one loops through the siblings in the object tree, the other
  1921.        through the tree in numerical order.
  1922.  
  1923.    (b) distinguishing productions (1) and (2) in
  1924.  
  1925.        printitem    ->    STRING
  1926.                           quantity                 (1)
  1927.                           ( form ) quantity        (2)
  1928.  
  1929.        i.e., between 
  1930.  
  1931.        print (routine-name) expression
  1932.        print (expression which happens to begin with a bracket)
  1933.  
  1934.        which requires N = 3.
  1935.  
  1936. The grammar contains one serious ambiguity: the innocent-looking production
  1937.  
  1938.        arrayvals    ->    constant arrayvals
  1939.  
  1940. means that array initialisations list constants in sequence without commas
  1941. or other separating characters.  This makes it impossible to distinguish
  1942. between unary and binary minus in a line like:
  1943.  
  1944.        Array X 2 - 1 ;     
  1945.  
  1946. The answer is "binary", since the grammar makes the longest match possible;
  1947. but a "this is ambiguous" warning is issued.
  1948.  
  1949. A further inconvenience in the grammar, though not much of an ambiguity,
  1950. occurs in the initialisation part of "for" statements: there is a danger of
  1951.  
  1952.        for (p=Class::)
  1953.  
  1954. being mis-parsed due to "::" being recognised as a binary operator (without
  1955. a right operand, which would cause an error) and not as two consecutive
  1956. ":" delimiters.
  1957.  
  1958. If I were free to redesign the Inform grammar in the light of the last
  1959. three years' experience (which I am loath to do, since so much Inform source
  1960. code now exists), here are the changes I think I would make:
  1961.  
  1962.        introduce commas as separators between array values and <<Action ...>>
  1963.            parameters;
  1964.        remove the statements quit, restore, save, style, font, spaces, box,
  1965.            inversion and read: the first three ought to be used via the
  1966.            assembler anyway, and the last six ought to be system-provided
  1967.            functions;
  1968.        use single quotes to refer to dictionary words used as values of "name",
  1969.            thus removing an anomalous rule going back to Inform 1, and to
  1970.            refer to dictionary words in grammar;
  1971.        find some notation for literal characters which does not look like
  1972.            the notation for dictionary words: e.g., ''z'' rather than 'z';
  1973.        abolish the distinction between actions and fake actions;
  1974.        rename the Global directive "Variable";
  1975.        require an = sign to be used in "Constant X 24" directives.
  1976.  
  1977.  
  1978.     5.4   Assigning values to symbols
  1979.           ---------------------------
  1980.  
  1981. Assigning values to symbols is the main way by which the syntax analyser
  1982. changes the way it will behave further on in the program.  From a strict
  1983. theoretical point of view one could insist the symbols table contains the
  1984. only information remembered by the syntax analyser about the program so far,
  1985. which otherwise churns out code which it forgets as soon as it has written:
  1986. however, Inform's analyser also keeps a number of other data structures,
  1987. such as the game dictionary and the object tree.
  1988.  
  1989. When the lexer creates a new symbol (that is, when the table is searched
  1990. for a string which isn't there, so that it is added to the table as a new
  1991. entry), it has:
  1992.  
  1993.     value   256
  1994.     type    CONSTANT_T
  1995.     flags   only UNKNOWN_SFLAG
  1996.     line    the current source line
  1997.  
  1998. "Unknown" means that the syntax analyser doesn't recognise it as meaning
  1999. anything yet.  The flag will only be cleared when the syntax analyser
  2000. assigns some value to the symbol (using the assign_symbol() routine), if ever.
  2001.  
  2002. The line is reset to the source line then applying if the symbol is assigned
  2003. a value, but is otherwise never changed.
  2004.  
  2005. The type and value of a symbol are only altered via assign_symbol().  With
  2006. one exception (see CHANGE_SFLAG below), the value once assigned is never
  2007. subsequently altered by reassignment.  Each symbol always has one of the
  2008. following 11 types:
  2009.  
  2010.     Type           Meaning                       Value
  2011.     ------------------------------------------------------------------------
  2012.     CONSTANT_T     Defined constant or           Value of constant
  2013.                        value not known yet
  2014.     LABEL_T        Name of label in source       Label number
  2015.     GLOBAL_VARIABLE_T
  2016.                    Name of global variable       Z-machine variable number
  2017.     ARRAY_T        Name of array                 Z-machine byte offset
  2018.                                                    in dynamic variables area
  2019.     ROUTINE_T      Name of routine               Scaled offset in Z-code
  2020.     ATTRIBUTE_T    Name of attribute             Z-machine attribute number
  2021.     PROPERTY_T     Name of common property       Z-machine property number
  2022.                                                    between 1 and 63
  2023.     INDIVIDUAL_PROPERTY_T
  2024.                    Name of indiv property        Property identifier >= 64
  2025.     OBJECT_T       Name of object                Z-machine object number - 1
  2026.     CLASS_T        Name of class                 Z-machine object number - 1
  2027.                                                    of its class-object
  2028.     FAKE_ACTION_T  Name of fake action           Action number >= 256
  2029.     ------------------------------------------------------------------------
  2030.  
  2031. The full list of symbol flags, and their meanings, is as follows:
  2032.  
  2033.     ------------------------------------------------------------------------
  2034.     UNKNOWN_SFLAG      no value has been assigned to this symbol
  2035.     USED_SFLAG         the value of this has been used in an expression
  2036.     REPLACE_SFLAG      the programmer has asked to Replace a routine
  2037.                            with this name
  2038.     DEFCON_SFLAG       this constant was defined by the "Default"
  2039.                            directive
  2040.     STUB_SFLAG         this routine was defined by the "Stub" directive
  2041.                            (similarly)
  2042.     INSF_SFLAG         this symbol was originally assigned a value in a
  2043.                            system_file
  2044.     SYSTEM_SFLAG       this symbol was assigned a value by Inform itself,
  2045.                            as one of the standard stock (such as "true"
  2046.                            or "recreate") provided to all programs
  2047.     UERROR_SFLAG       a "No such constant as this" error has already been
  2048.                            issued for this name
  2049.     ALIASED_SFLAG      this is an attribute or property name whose value
  2050.                            is shared with another attribute or property name
  2051.     CHANGE_SFLAG       this is a defined Constant whose value needs later
  2052.                            backpatching, or is a Label whose label number
  2053.                            has been allocated before its declaration in the
  2054.                            code
  2055.     ACTION_SFLAG       this is a ## name (of an action or a fake action)
  2056.     REDEFINABLE_SFLAG  the symbol can be defined more than once using the
  2057.                            "Constant" directive, without errors being
  2058.                            produced.  (Used for the special constants DEBUG,
  2059.                            USE_MODULES, MODULE_MODE and Grammar__Version.)
  2060.     ------------------------------------------------------------------------
  2061.     IMPORT_SFLAG       this name is "imported" (used in module compilation)
  2062.     EXPORT_SFLAG       this name was "exported" from some module
  2063.                            (used in story file compilation)
  2064.     ------------------------------------------------------------------------
  2065.  
  2066. USED_SFLAG is used only to decide whether or not to issue "declared but not
  2067. used" warnings.  A symbol has been "used" if one of the following is true:
  2068.  
  2069.     (i)    its value occurred in an expression;
  2070.     (ii)   it has been assigned, and tested with IFDEF or IFNDEF;
  2071.     (iii)  it's an action routine name used in grammar or via ##
  2072.            (e.g. use of ##Take causes TakeSub to be "used");
  2073.     (iv)   it's a fake action name used via ##;
  2074.     (v)    it's a property, attribute or class name used in an
  2075.            object or class definition;
  2076.     (vi)   it's a label name branched to in assembly language or
  2077.            the destination of a "jump" statement;
  2078.     (vii)  it's the routine name "Main";
  2079.     (viii) it's a routine name referred to by the obsolete #r$
  2080.            construct;
  2081.     (ix)   it's a routine name of a veneer routine whose definition
  2082.            is being over-ridden in the source code, and to which a
  2083.            call has been compiled;
  2084.     (x)    it's a routine name used in a grammar token;
  2085.     (xi)   it's referred to in a module which has been linked into
  2086.            the story file being compiled.
  2087.  
  2088. Note that such warnings are not issued for object names, since in much
  2089. Inform 5 code objects are given irrelevant object symbol-names (the syntax
  2090. required it); nor for symbols defined by Inform, or in the veneer, or in
  2091. a system file.  Warnings are never issued (except for labels and local
  2092. variables, which have local scope) when compiling modules, since there is
  2093. no way of knowing at compile time which exported symbols will be used and
  2094. which will not.
  2095.  
  2096. The warnings are issued at the end of the source code pass, but before the
  2097. veneer is compiled.  The slines[] array is used to work out which source
  2098. lines to report from.
  2099.  
  2100. CHANGE_SFLAG is used when definitions such as:
  2101.  
  2102.     Constant frog_word = 'frog';
  2103.  
  2104. are reached, where the value (the dictionary address for 'frog') cannot
  2105. immediately be known.  Such symbol values are backpatched later as needed.
  2106.  
  2107.  
  2108. All symbols in the table have "global scope" (that is, their definitions are
  2109. valid everywhere in the source program) except for label names, whose scope
  2110. is restricted to the current routine.  Thus, the same label name can be used
  2111. in many different routines, referring to a different label in each.
  2112.  
  2113. To achieve this, the routine-end routine in "asm.c" cancels the assignment
  2114. of label names, returning them to type CONSTANT_T and flag UNKNOWN_SFLAG.
  2115.  
  2116. Local variables also have local scope, but for efficiency reasons these are
  2117. not stored in the symbols table but in a special hash table in level 3 of
  2118. the lexer.
  2119.  
  2120.  
  2121. Note that action names have a different "name-space" from other symbols:
  2122. this is why the library's action name "Score" is never confused with its
  2123. variable "score".  Rather than use a different symbols table altogether,
  2124. actions are stored as integer constants in the form
  2125.  
  2126.     Score__A
  2127.  
  2128. (thus the value of this symbol is the value ##Score).  Similarly, fake
  2129. actions are stored this way (but with type FAKE_ACTION_T rather than
  2130. INTEGER_CONSTANT_T); both forms of symbol are flagged ACTION_SFLAG.
  2131.  
  2132.  
  2133.     5.5   Outputs other than assembly language
  2134.           ------------------------------------
  2135.  
  2136. Below the parse_routine() part of the syntax analyser, the only output is
  2137. assembly language (together with dictionary words and encoded text as needed
  2138. within it).
  2139.  
  2140. However, parse_directive() has several other outputs, as shown on the source
  2141. code map (section 1.2 above).  Directives create objects to be remembered and
  2142. written into the final program: arrays, verb definitions, actions, objects
  2143. and so on.  These will be called "program elements".
  2144.  
  2145. Directives also "create" constants, attributes, properties and fake actions,
  2146. but in these cases creation only consists of assigning a suitable value to a
  2147. symbol.  So these do not count as program elements.
  2148.  
  2149. The data structures to hold "program elements" are all created and maintained
  2150. within "directs.c" and its subsidiaries (such as "objects.c", the
  2151. object-maker); they are then translated into a usable Z-machine form in
  2152. "tables.c".  (With only trivial exceptions, the data structures are not
  2153. accessed anywhere else in Inform.)
  2154.  
  2155.     ---------------------------------------------------------------
  2156.     Program element      Section      Name of (main) data structure
  2157.     ---------------------------------------------------------------
  2158.     Global variable      arrays.c     global_initial_value[]
  2159.     Array                arrays.c     dynamic_array_area[]
  2160.     Release number       directs.c    release_number
  2161.     Serial code          directs.c    serial_code_buffer[]
  2162.     Statusline flag      directs.c    statusline_flag
  2163.     Object tree          objects.c    objects[]
  2164.     Common property      objects.c    prop_default_value[]
  2165.       default value
  2166.     Class-to-object-     objects.c    class_object_numbers[]
  2167.       numbers table              
  2168.     Common property      objects.c    *properties_table
  2169.       values for
  2170.       objects
  2171.     Individual prop      objects.c    *individuals_table
  2172.       values for
  2173.       objects
  2174.     Table of static      symbols.c    individual_name_strings[]
  2175.       string values
  2176.       for property
  2177.       names
  2178.     And attribute names  symbols.c    attribute_name_strings[]
  2179.     And action names     symbols.c    action_name_strings[]
  2180.     Abbreviation         text.c       abbreviations_at[]
  2181.       table entry
  2182.     Grammar table        verbs.c      Inform_verbs[]
  2183.     Token-routine        verbs.c      grammar_token_routine[]
  2184.       addresses
  2185.     List of dict         verbs.c      adjectives[]
  2186.       addresses for
  2187.       "adjective" words
  2188.     Action routine       verbs.c      action_byte_offset[]
  2189.       addresses
  2190.     ---------------------------------------------------------------
  2191.  
  2192. A rather unequal gathering: the storage required to hold the common property
  2193. values table may be as much as 32K, whereas the statusline flag can be held
  2194. in 1 bit.
  2195.  
  2196. There are three other program elements: Z-code, kept by "asm.c"; the static
  2197. strings of Z-encoded text, kept by "text.c"; and the dictionary, also kept by
  2198. "text.c".
  2199.  
  2200.  
  2201.     5.6   Assembly operands
  2202.           -----------------
  2203.  
  2204. The type "assembly_operand" is used for all numerical values (and local or
  2205. global variable references) which are destined one day to be written into the
  2206. Z-machine.  Many of these will indeed be operands in Z-code instructions,
  2207. hence the name.  Others will be property values, array entries and so on.
  2208.  
  2209. The definition is:
  2210.  
  2211.     {   int   type;
  2212.         int32 value;
  2213.         int   marker;
  2214.     }
  2215.  
  2216. which is a pretty generous memory allocation for holding a signed 16-bit
  2217. number.  (However, there are no large arrays of this type; type and marker
  2218. could easily each have type char, but I suspect this would be slower because
  2219. of alignment problems on some compilers; and speed does matter here.)
  2220.  
  2221. The possible types are:
  2222.  
  2223.     SHORT_CONSTANT_OT       number with value between 0 and 255
  2224.     LONG_CONSTANT_OT        number with any 16 bit value
  2225.     VARIABLE_OT             reference to the stack pointer if value is 0
  2226.                             local variable if value 1 to 15
  2227.                             global variable if value 16 to 255
  2228.  
  2229. In addition, two special types are in use by the expression parser:
  2230.  
  2231.     OMITTED_OT              (the operand holds no information)
  2232.     EXPRESSION_OT           reference to a parse tree
  2233.  
  2234. The "marker" value is used to record the origin of the data, which is
  2235. essential to make backpatching work.  For example, in the line
  2236.  
  2237.     v = "Jackdaws love my big sphinx of quartz";
  2238.  
  2239. the right operand is marked with STRING_MV, because the value which needs
  2240. to be stored in the Z-machine is a packed string address and this cannot be
  2241. known until after the compilation pass (when the size of the tables and
  2242. the code area are known).  Wherever the operand is written, in code or in
  2243. a table, "bpatch.c" will later find and correct it.
  2244.  
  2245.  
  2246.     5.7   Translation to assembly language
  2247.           --------------------------------
  2248.  
  2249. The Z-machine has a very easy architecture to generate code for.  Most
  2250. compilers' syntax analysers generate a "three-address code" as an
  2251. intermediate stage towards final object code; this is a sequence of
  2252. instructions in the form
  2253.  
  2254.     x = y <operator> z
  2255.  
  2256. together with conditional branches and labelled points to branch to.  (See
  2257. ASU, p.466.)  Translating this code into assembly language for some CPU
  2258. is a further compilation phase: the tricky part is not translating the
  2259. operators into instructions, but deciding where to locate the values
  2260. x, y and z.  On most CPUs, a limited number of registers can hold values, and
  2261. arithmetic operations can only be performed on these registers; moreover,
  2262. holding data in a register is much more efficient than holding it elsewhere.
  2263. The problem is therefore to allocate registers to quantities, and the
  2264. performance of the compiled code depends very heavily on how well this is
  2265. done.  (Register allocation is far from being a solved problem in the way
  2266. that lexical analysis, say, is considered to be.)
  2267.  
  2268. What makes the Z-machine particularly easy is that its instruction set is
  2269. more or less three-address code already.  Arithmetic can be performed with
  2270. constants as operands as well as with "registers"; and not only is every
  2271. local or global variable automatically allocated to a register of its own,
  2272. but a stack is available to hold intermediate values (and with no performance
  2273. penalty for its use, since it is accessible as though it were a register).
  2274.  
  2275. The key point to remember when looking at Z-code is that writing a value to
  2276. the "stack-pointer variable" pushes it onto the Z-machine stack; using the
  2277. "stack-pointer variable" as the operand for an instruction pulls the value
  2278. being read off the stack.
  2279.  
  2280.  
  2281. Despite the availability of the stack, it's still convenient to have a few
  2282. spare variables to use as "registers" holding temporary values.  Inform
  2283. reserves the variables 249, 250, 251, ..., 255 for its own use: though this
  2284. slightly exaggerates the position, since two of these are used for the
  2285. variables "self" and "sender".  One more is used to hold the switch-value
  2286. of the current switch statement (if there is one); the remaining four in
  2287. order to implement various system functions (such as "children") with
  2288. inline-code rather than routine calls to the veneer.  (The one inconvenience
  2289. with the Z-machine's instruction set is that there's no good way to read the
  2290. top of the stack non-destructively, or to duplicate the top value, or to
  2291. reorder the top few values.)
  2292.  
  2293.  
  2294. The syntax analyser produces code by making function calls to the assembler.
  2295. There are four types of function call:
  2296.  
  2297.     assemble_routine_header(...)
  2298.     assemble_routine_end(...)
  2299.  
  2300. at the start and end of every routine;
  2301.  
  2302.     assemble_label_no(N)
  2303.  
  2304. to indicate that the Nth label belongs here (i.e., at the point where the
  2305. next instruction will be put); and then a fair variety of function calls
  2306. to generate actual instructions.  For example,
  2307.  
  2308.     assemble_jump(N)
  2309.  
  2310. assembles an unconditional jump to label N.  A typical "three-address code"
  2311. is assembled by a routine like
  2312.  
  2313.     assemble_2_to(mul_zc, AO1, AO2, stack_pointer)
  2314.     
  2315. meaning "the instruction mul_zc, which has 2 operands and has a result which
  2316. it writes to the variable indicated by the third operand".  AO1 and AO2
  2317. are assembly_operands (the abbreviation is often used in the source), and
  2318. so is stack_pointer (it has type VARIABLE_OT and value 0).
  2319.  
  2320.  
  2321. A typical example of how the top-down syntax analyser generates code is
  2322. given by the code for the "while" statement:
  2323.  
  2324.         case WHILE_CODE:
  2325.                  assemble_label_no(ln = next_label++);
  2326.                  match_open_bracket();
  2327.  
  2328.                  code_generate(parse_expression(CONDITION_CONTEXT),
  2329.                      CONDITION_CONTEXT, ln2 = next_label++);
  2330.                  match_close_bracket();
  2331.  
  2332.                  parse_code_block(ln2, ln, 0);
  2333.                  assemble_jump(ln);
  2334.                  assemble_label_no(ln2);
  2335.                  return;
  2336.  
  2337. Note that this expects to match
  2338.  
  2339.         while ( condition ) statement
  2340.                             or { statements }
  2341.  
  2342. The expression parser is called to turn the condition into a parse tree,
  2343. and its output is fed straight into the code generator for parse trees.
  2344.  
  2345. The label numbers ln2 and ln are supplied to the routine for parsing code
  2346. blocks because they indicate which labels the statements "break" and
  2347. "continue" should generate jumps to.
  2348.  
  2349. For example,
  2350.  
  2351.         while (i <= 10) print i++;
  2352.  
  2353. generates the assembly language
  2354.  
  2355.         .L0;    @jg i 10 ?L1;
  2356.                 @inc i;
  2357.                 @print_num i;
  2358.                 @jump L0;
  2359.         .L1;    
  2360.  
  2361. In terms of function calls to "asm.c":
  2362.  
  2363.         assemble_label_no(0);
  2364.         assemble_2_branch(jg_zc, AO_for_i, AO_for_10, 1, TRUE);
  2365.         assemble_inc(AO_for_i);
  2366.         assemble_1(print_num_zc, AO_for_i);
  2367.         assemble_jump(0);
  2368.         assemble_label_no(1);
  2369.  
  2370. (Note that incrementing is needed so often that assemble_inc() is provided
  2371. as a shorthand: actually also because of a form of indirect addressing used
  2372. by the Z-machine for store_zc and inc_zc, dec_zc.  assemble_store() and
  2373. assemble_dec() are also provided.)
  2374.  
  2375.  
  2376.     5.8   Summary of assembly language instructions output
  2377.           ------------------------------------------------
  2378.  
  2379. The list of Z-machine instructions which Inform actually generates code for
  2380. by itself is quite short (about half of the 115 possible instructions are
  2381. ever used).  The assembly-language "@ statement" parser can, of course,
  2382. generate every Z-machine instruction.
  2383.  
  2384. The instructions used for three-address-style code (that is, for program
  2385. control, arithmetic, etc.) are as follows.  For function calls and returns,
  2386. unconditional jumps and for moving values between variables, memory locations
  2387. and the stack:
  2388.  
  2389.     call_*          rfalse            rtrue             ret_popped
  2390.     ret             inc               dec               store
  2391.     push            pull              storeb            storew
  2392.     loadb           loadw             jump
  2393.  
  2394. (There are various forms of call instruction to do with the number of
  2395. operands, whether a return value is wanted or not, etc.).  Six conditional
  2396. branch instructions are used:
  2397.  
  2398.     je              jz                jl                jg
  2399.     jin             test_attr         check_no_args
  2400.  
  2401. (the first four are numerical branches, the next two related to the object
  2402. tree, and the last one is used only in V5 or later games, and then only
  2403. for printing out tracing code): note that each can also be used in a
  2404. "negate this condition" form.  Finally, signed 16-bit arithmetic and
  2405. unsigned 16-bit bitwise operations:
  2406.  
  2407.     add             sub               mul               div
  2408.     mod             and               or                not
  2409.  
  2410.  
  2411. A further batch of instructions is used, so to speak, in lieu of calls to a
  2412. standard library of input/output and utility routines (like C's "stdio"):
  2413.  
  2414.     print           print_ret         print_char        print_num      
  2415.     print_addr      print_paddr       print_obj         new_line
  2416.     insert_obj      remove_obj        get_parent        get_child
  2417.     get_sibling     get_prop          get_prop_addr     get_prop_len
  2418.     put_prop        random            aread/sread       quit
  2419.     save            restore           output_stream
  2420.  
  2421. with five more exotic screen control instructions used only if a "box"
  2422. statement is ever compiled:
  2423.  
  2424.     split_window    set_window        style             set_cursor
  2425.     buffer_mode
  2426.  
  2427.     
  2428.     6   Syntax analysis 2: the bottom-up expression parser
  2429.         --------------------------------------------------
  2430.  
  2431.     6.1   Map and structure
  2432.           -----------------
  2433.  
  2434. It would be possible to continue the top-down parser down into the level of
  2435. expressions: for instance, to have a routine parse_plus() which would
  2436. parse_expression(), then match a plus sign, then parse_expression() again,
  2437. and so on.  This would however be highly inefficient in terms of function
  2438. calls, difficult to recover from when an error occurs, and require either
  2439. much greater lookahead or rather complicated mechanisms for storing parse
  2440. trees.
  2441.  
  2442. Expressions (including assignments, conditions and constant values) are
  2443. therefore parsed by a different syntax analyser, which is "bottom up" (it
  2444. begins by reading in the tokens, and only works out what they mean afterward)
  2445. rather than "top down" (starting from an assumption about the meaning and
  2446. then trying to find the evidence to justify it).
  2447.  
  2448. The algorithm used is an operator precedence parser, a simple form of
  2449. shift-reduce parser.  There is alas no space to describe this beautiful
  2450. algorithm here: see ASU, pp.195-215.  In this account we treat it as a
  2451. "black box".
  2452.  
  2453. The expression parser "expressp.c" has the structure:
  2454.  
  2455.     -------->  "Level 4" of      -------->  Operator
  2456.      tokens    lexical analysis   etokens   precedence
  2457.        in                                   parser
  2458.                                               |
  2459.                                               | etokens re-ordered into RPN
  2460.                                              \|/ 
  2461.                                             Emitter
  2462.                                               |
  2463.                                               | plain parse tree
  2464.                                              \|/ 
  2465.                                             Lvalue and
  2466.                                             condition checking
  2467.                                               |
  2468.                                               | more detailed parse tree
  2469.                                              \|/         out
  2470.  
  2471. (This is effectively a magnification of the part of the source map in
  2472. section 1.2 above which reads just "expressp.c".)  Note that there is a
  2473. single input and a single output channel.
  2474.  
  2475. RPN is "reverse Polish notation": for example
  2476.  
  2477.     (2 + 4)*45 + 34         becomes  2 4 + 45 * 34 +
  2478.  
  2479. the idea being that one reads it left to right: each number is added to
  2480. a stack of numbers, and each operation takes some numbers off the stack
  2481. and puts an answer back.  (E.g., + takes 2 and 4 off and replaces them
  2482. with 6.  * takes 6 and 45 off, replacing them with 270.  + takes 34 and 270
  2483. off, replacing them with 304, which is the answer.)  The advantage of
  2484. this is that is unambiguous which operator acts on which operands, and the
  2485. brackets have gone.
  2486.  
  2487. The emitter builds a (plain) parse tree out of this sequence, as follows.
  2488. It stacks 2 and then 4:
  2489.  
  2490.     Stack: 2 4
  2491.  
  2492. It reads +, which it knows has two operands, and takes the top two items
  2493. off the stack, joining them into a tree segment like so:
  2494.  
  2495.                       +
  2496.                      / \
  2497.                     2   4
  2498.  
  2499. It then makes a special value, say E1, meaning "the sub-expression in this
  2500. tree", and stacks that:
  2501.  
  2502.     Stack: E1
  2503.  
  2504. It then stacks up 45, and reaches *: it takes off the top two values, which
  2505. are E1 and 45, and makes
  2506.  
  2507.                       *
  2508.                      / \
  2509.                    E1   45
  2510.  
  2511. which it calls E2, and so on.  When the process is finished, we have the
  2512. tree:
  2513.                             +   <--- this is E3
  2514.                            / \
  2515.         this is E2 --->   *   34
  2516.                          / \
  2517.       this is E1 --->   +   45
  2518.                        / \
  2519.                       2   4
  2520.  
  2521. and the stack contains just E3, which is the "answer".
  2522.  
  2523.  
  2524.     6.2   The operator precedence grammar
  2525.           -------------------------------
  2526.  
  2527. A list of productions for this grammar would be tiresomely long.  It can
  2528. be roughly summarised as:
  2529.  
  2530.     expression   ->   ( expression )
  2531.                       a single operator acting on some operands in some way
  2532.     operand      ->   token representing a constant
  2533.                       ( expression )
  2534.                       expression ( arguments )
  2535.     arguments    ->   <empty>
  2536.                       expression , arguments
  2537.  
  2538. The tokens representing a constant are given in the next section.  The
  2539. operators have tokens as follows:
  2540.  
  2541.     --------------------------------------------------------------------------
  2542.     Level    Lexeme    Usage   Associativity  Purpose
  2543.     --------------------------------------------------------------------------
  2544.       0      ,         binary  left           separating values to work out
  2545.  
  2546.       1      =         binary  right          set equal to
  2547.  
  2548.       2      &&        binary  left           logical AND
  2549.       2      ||        binary  left           logical OR
  2550.       2      ~~        unary   (prefix)       logical NOT
  2551.  
  2552.       3      ==        binary  none           equal to?
  2553.       3      ~=        binary  none           not equal to?
  2554.       3      >         binary  none           greater than?
  2555.       3      >=        binary  none           greater than or equal to?
  2556.       3      <         binary  none           less than?
  2557.       3      <=        binary  none           less than or equal to?
  2558.       3      has       binary  none           object has this attribute?
  2559.       3      hasnt     binary  none           object hasn't this attribute?
  2560.       3      in        binary  none           first obj a child of second?
  2561.       3      notin     binary  none           first obj not a child of second?
  2562.       3      ofclass   binary  none           obj inherits from class?
  2563.       3      provides  binary  none           obj provides this property?
  2564.  
  2565.       4      or        binary  left           separating alternative values
  2566.  
  2567.       5      +         binary  left           16-bit signed addition
  2568.       5      -         binary  left           16-bit signed subtraction
  2569.  
  2570.       6      *         binary  left           16-bit signed multiplication
  2571.       6      /         binary  left           16-bit signed integer division
  2572.       6      %         binary  left           16-bit signed remainder
  2573.       6      &         binary  left           bitwise AND
  2574.       6      |         binary  left           bitwise OR
  2575.       6      ~         unary   (prefix)       bitwise NOT
  2576.  
  2577.       7      ->        binary  left           byte array entry
  2578.       7      -->       binary  left           word array entry
  2579.  
  2580.       8      -         unary   (prefix)       16-bit (signed!) negation
  2581.  
  2582.       9      ++        unary   (pre/postfix)  read/increment or increment/read
  2583.       9      --        unary   (pre/postfix)  read/decrement or decrement/read
  2584.  
  2585.      10      .&        binary  left           property address
  2586.      10      .#        binary  left           property length
  2587.      10      ..&  (**) binary  left           individual property address
  2588.      10      ..#  (**) binary  left           individual property length
  2589.  
  2590.     11/14    ( )       binary  left           function call/message send
  2591.  
  2592.      12      .         binary  left           property value
  2593.      12      ..   (**) binary  left           individual property value
  2594.  
  2595.      13      ::        binary  left           "superclass" operator
  2596.     --------------------------------------------------------------------------
  2597.     (**): Illegal except internally, in Inform's own source for the run-time
  2598.           veneer
  2599.     --------------------------------------------------------------------------
  2600.  
  2601. Note that, unlike C, Inform does not provide unary plus.
  2602.  
  2603. A binary infix operator is used in the form "X op Y"; a unary prefix operator
  2604. in the form "op X"; a unary postfix operator in the form "X op".
  2605.  
  2606. The "level" is the precedence level: the higher this number, the more tightly
  2607. an operator is glued to the operands adjacent to it.
  2608.  
  2609. Cases where two binary infix operators have equal precedence are resolved
  2610. according to whether that level is left or right associative.  For instance,
  2611.  
  2612.    a / b / c      means    (a/b)/c
  2613.  
  2614. since /, on level 6, is left associative.  But
  2615.  
  2616.    a = b = c      means    a = (b = c)
  2617.  
  2618. since =, on level 1, is right associative.
  2619.  
  2620. Cases in the above table where the associativity is "none" mean that an
  2621. attempt to silently associate the operator will cause an error.  For example,
  2622.  
  2623.    a == b == c
  2624.  
  2625. generates an error as being ambiguous, but
  2626.  
  2627.    (a == b) == c   and   a == (b == c)
  2628.  
  2629. are both permitted.
  2630.  
  2631. The function-call-brackets have an asymmetric precedence level according
  2632. to whether they're being compared with something on the left or on the right:
  2633. the point is that
  2634.  
  2635.     object.message(...)
  2636.     function_returning_an_object(...).property
  2637.  
  2638. must be recognised as
  2639.  
  2640.     (object.message)(...)                               . 12      >  (...) 11
  2641.     (function_returning_an_object(...)).property        (...) 14  >  . 12
  2642.  
  2643. respectively.
  2644.  
  2645.  
  2646.     6.3   Lexical level 4: tokens to etokens
  2647.           ----------------------------------
  2648.  
  2649. The shift-reduce parser expects tokens sorted out into operators, such as
  2650. "+" or "ofclass", operands such as "34" or "score" (assuming that's a
  2651. variable) and three tokens of special significance:
  2652.  
  2653.     (     )     end-of-expression
  2654.  
  2655. "Level 4 of the lexer" does just this.  It converts the stream output from
  2656. "lexer.c" (i.e., from level 3) into a stream of tokens from the following
  2657. table (and it uses a good deal of context information to do so).
  2658.  
  2659.     Token type           Meaning
  2660.     -------------------------------------------------------------------------
  2661.     OP_TT                Operator: value is a *_OP constant
  2662.  
  2663.     LARGE_NUMBER_TT      Operand (number): value is the number
  2664.     SMALL_NUMBER_TT      Operand (number guaranteed in the range 0 to 255):
  2665.                              value is the number
  2666.     VARIABLE_TT          Operand: value is Z-machine variable number
  2667.     DQ_TT                Operand (text used as static string): text in text
  2668.     DICTWORD_TT          Operand (text used as dictionary word): text in text
  2669.     ACTION_TT            Operand (##action number): name of action in text
  2670.     SYSFUN_TT            Operand (system fn name): value is a *_SYSF constant
  2671.     SYSTEM_CONSTANT_TT   Operand (#system_constant): value is a *_SC constant
  2672.  
  2673.     SUBOPEN_TT           Open bracket used to open a sub-expression
  2674.     SUBCLOSE_TT          Close bracket used to close a sub-expression
  2675.  
  2676.     ENDEXP_TT            End of expression
  2677.     -------------------------------------------------------------------------
  2678.  
  2679. The tokens in this output stream are called "etokens", short for "expression
  2680. tokens": they are the raw material from which parse trees are built up.
  2681. (Although formally different from ordinary tokens, they have the same storage
  2682. type, "token_data", in the Inform source code.)
  2683.  
  2684. At first sight this seems an unnecessarily large stock: why not, for example,
  2685. compile static strings and dictionary words and convert them to their
  2686. addresses here and now?  Why not evaluate system constants and action numbers
  2687. now?  Because: (i) these tokens may not be accepted by the parser, so we
  2688. can't compile text on the strength of them (and indeed, the parse tree which
  2689. is being parsed may not ever be code-generated from); and (ii) we can't
  2690. allow ourselves to lose sight of where numbers are coming from so soon,
  2691. or backpatching will be impossible.
  2692.  
  2693.  
  2694. The presence of two different tokens for numbers - one for numbers guaranteed
  2695. to be unsigned 8 bit, one for numbers with no such guarantee and whose value
  2696. may be any signed 16 bit quantity - is due to the architecture of the target
  2697. Z-machine.  In Z-code considerable space savings are made by storing small
  2698. numbers in 1, rather than 2, bytes.  We are anxious to take advantage of
  2699. this.
  2700.  
  2701. Unfortunately, what seems to be a small number now may not be a small number
  2702. later (after backpatching).  Dictionary word values (such as 'word') are
  2703. internally stored as the accession number of that word into the dictionary
  2704. (say 23, if it is the 23rd different word to be entered) during the
  2705. compilation pass, and then backpatched later to the byte address of this
  2706. word's dictionary entry: but this will be a large number.
  2707.  
  2708. Most operands with non-NULL backpatch markers are forced into long form, to be
  2709. on the safe side.  (This includes all operands which are forward references
  2710. to constants not yet defined.)  The exceptions are that variable and action
  2711. numbers (though not fake action numbers) are guaranteed always to fit into
  2712. short form.
  2713.  
  2714.  
  2715. There are two tasks involved in translating tokens to etokens: evaluating
  2716. tokens representing quantities into one of the "operand" etokens, and sorting
  2717. other tokens into the right operator and special etokens.  The second process
  2718. is not as easy as it looks because of ambiguities, and is discussed in the
  2719. next section.  This section discusses the evaluation of quantity tokens.
  2720.  
  2721. Tokens in expressions are read in a context where the keywords are local
  2722. variables, textual operators, system function names and system constant
  2723. names.  Other identifiers are symbol names.  So the token types which must
  2724. represent quantities are:
  2725.  
  2726.     DQ_TT, SQ_TT, LOCAL_VARIABLE_TT, NUMBER_TT,
  2727.     SYMBOL_TT, SYSFUN_TT and SYSTEM_CONSTANT_TT.
  2728.  
  2729. (Actually, this omits a detail: the largely obsolete constant forms #a$...,
  2730. #r$..., #n$... are SEP_TT tokens converted into the above; and the very much
  2731. still with us constant form ##... is a SEP_TT token converted
  2732. straightforwardly into the ACTION_TT etoken.)
  2733.  
  2734. These all translate directly into etokens except for SYMBOL_TT and SQ_TT.
  2735. SQ_TT requires a little work because of the Inform syntax for single-quoted
  2736. strings:
  2737.  
  2738.     'x'        means the character code (i.e. ASCII value) for "x"
  2739.     '@ss'      means the character code for the German letter "sz"
  2740.                (i.e. the code specified in the accented set in the
  2741.                Z-Machine standard document)
  2742.     'xyzzy'    means the byte address of the dictionary word "xyzzy"
  2743.  
  2744. The first two become SMALL_NUMBER_TT etokens.  The third becomes a
  2745. DICTWORD_TT etoken.
  2746.  
  2747.  
  2748. This leaves SYMBOL_TT tokens: names for constants.  There are two
  2749. possibilities: the symbol is so far unknown, or else it has been assigned
  2750. a value in earlier syntax analysis.
  2751.  
  2752. In most languages it would be an error to use an unknown symbol name as
  2753. a value: in C, for example, a function name cannot be used in an expression
  2754. unless it has been declared beforehand.
  2755.  
  2756. Inform is more tolerant: as far as expressions are concerned, any symbol can
  2757. be used earlier than the point in the source code where its value is
  2758. assigned, excepting only a local or global variable name.  (This exception
  2759. is mainly for Z-machine architecture reasons, but it also makes Inform code
  2760. more legible.)
  2761.  
  2762. When an unknown symbol is reached, it is converted to a LARGE_NUMBER_TT and
  2763. marked as SYMBOL_MV, with the value being its index in the symbol table.
  2764. (This allows the backpatcher to know where to find the true value later.)
  2765.  
  2766. When a known symbol is reached which is flagged as CHANGE_SFLAG, this is
  2767. treated in the same way.  (CHANGE_SFLAG is given to symbols defined by
  2768. Constant definitions whose values themselves require backpatching: for
  2769. instance, symbols defined equal to dictionary words or routine addresses.)
  2770.  
  2771. Otherwise, the symbol is not only known, but its current value is known to
  2772. be correct, and so:
  2773.  
  2774.     if it's a variable, it's translated to etoken VARIABLE_TT;
  2775.     otherwise the LARGE_NUMBER_TT/SMALL_NUMBER_TT decision is now made:
  2776.         if it is marked with a marker other than VARIABLE_MV, it becomes
  2777.             "long";
  2778.         otherwise the value is compared with the range 0 to 255.
  2779.  
  2780. Any symbol name fed into the shift-reduce parser is flagged with USED_SFLAG
  2781. to indicate that its value has at some point been used in an expression.
  2782. (This information enables "This ... was declared but not used" warnings to be
  2783. made at the end of compilation.)
  2784.  
  2785.  
  2786.     6.4   Resolution of ambiguous tokens
  2787.           ------------------------------
  2788.  
  2789. It remains to translate to the etokens OP_TT, SUBOPEN_TT, SUBCLOSE_TT and
  2790. ENDEXP_TT.  The token types which represent operators are all from SEP_TT and
  2791. COND_TT; open and close bracket are also SEP_TT tokens.
  2792.  
  2793. There are two main difficulties here.  Firstly, shift-reduce parsers are
  2794. unsuitable for resolving ambiguities, and so it is not possible to map tokens
  2795. directly into operators.  The ambiguities in the expression grammar for
  2796. Inform are:
  2797.  
  2798. (a)  ++ and -- each refer to either a prefix or a postfix operator
  2799. (b)  - refers to either a unary prefix operator or a binary infix one
  2800. (c)  ( and ) are used both to indicate function calls and subexpressions
  2801. (d)  , is used both to indicate a sequence of values, each to be evaluated
  2802.         and thrown away with only the last one kept, and to separate
  2803.         function arguments
  2804. (e)  -> does not represent an operator when parsing constants as operand
  2805.         values in a line of "@" assembly language (because it needs to
  2806.         mean "the store value goes in")
  2807.  
  2808. These are resolved as follows:
  2809.  
  2810. (a), (b)  The "level 4 lexer" watches for context: for instance, MINUS_SEP
  2811.           translates to UNARY_MINUS_OP if there was no previous token, or
  2812.           it was an open bracket, or an infix or prefix operator, or a
  2813.           comma; otherwise it translates to MINUS_OP.
  2814.  
  2815.      (c)  Similarly. If an open bracket token is read, and the previous
  2816.           token was an operand of some kind, then it must represent a
  2817.           function call (unless we are in constant context); an extra
  2818.           etoken is generated for an imaginary infix operator called
  2819.           FCALL_OP.  The open bracket token is then translated to
  2820.           SUBOPEN_TT as usual; a close bracket is always SUBCLOSE_TT. Thus,
  2821.           the stream
  2822.  
  2823.               Eroica ( Beethoven , 3 )
  2824.  
  2825.           is translated into the etokens
  2826.  
  2827.               Eroica <fcall> ( Beethoven <comma> 3 )
  2828.  
  2829.           so that a tree will come out of the emitter looking like
  2830.           
  2831.                      <fcall>
  2832.                      /     \
  2833.                  Eroica   <comma>
  2834.                           /     \
  2835.                       Beethoven  3
  2836.  
  2837.           although in fact the emitter recognises what is going on and
  2838.           automatically simplifies this to:
  2839.  
  2840.                        <fcall>
  2841.                       /   |   \
  2842.                      /    |    \
  2843.                Eroica Beethoven 3
  2844.  
  2845.      (d)  A comma at the top level is either disallowed (in constant context)
  2846.           or treated as the operator <evaluate from left to right but throw
  2847.           away the result on the left and keep the one on the right>.  (Just
  2848.           as in C.)  Otherwise, comma is a separator of arguments.  "Top
  2849.           level" means "top bracket level", which the "level 4 lexer" keeps
  2850.           track of by counting the bracket tokens going through it.
  2851.  
  2852.      (e)  There is a special expression context called "assembly language",
  2853.           in which "->" is translated to ENDEXP_TT.
  2854.  
  2855.  
  2856. The second main difficulty is entirely of the language designer's own making. 
  2857. How is the end of an expression to be detected?  In C, it always possible
  2858. when parsing an expression to say "the end will have been reached when
  2859. such-and-such a token is reached": for example, ";" or "}".  This is not
  2860. possible in Inform.
  2861.  
  2862. Even if one knows in advance what the terminating token ought to be, it might
  2863. be impossible to recognise for context reasons.  For example, the statement
  2864.  
  2865.     move <first expression> to <second expression>;
  2866.  
  2867. appears to be no problem: the first expression is terminated by the keyword
  2868. "to", the second by ";".  But suppose "to" has another meaning, as the name
  2869. of a constant or variable?  In this case,
  2870.  
  2871.     move 2 + to to to;
  2872.  
  2873. is a legal statement.
  2874.  
  2875. For all these reasons, Inform actually detects the end of an expression at
  2876. lexical level 4 by watching the context carefully: for instance, in
  2877.  
  2878.     move 4 * banana to ...
  2879.  
  2880. when "4 * banana" has been passed, the next token is expected to be an open
  2881. bracket, an infix or postfix operator, or (perhaps) a comma.  Since the next
  2882. token is none of these, the expression has ended.  Note that this decision
  2883. can be taken without knowing whether "to" is a keyword or a symbol.
  2884.  
  2885.  
  2886. From a grammatical point of view the worst design flaw in the Inform language
  2887. is that array initialisations (either in Array directives or object property
  2888. values) consist of sequences of expressions given without any separator in
  2889. between.  For example,
  2890.  
  2891.     Array X --> 2 4 6 * MAX_FROGS 45 ;
  2892.  
  2893. This is arguably a convenient shorthand.  Unfortunately, it falls prey to
  2894. that predator of all computing grammars, unary minus.  The directive
  2895.  
  2896.     Array X --> 10 -5;
  2897.  
  2898. is ambiguous.  Is it an array of 10-5 = 5 entries, or an array of two entries,
  2899. 10 and -5?
  2900.  
  2901. In Inform 5 there was no problem since constants were not allowed to contain
  2902. operators anyway (and negative numbers were represented by single tokens,
  2903. which is not true in Inform 6): the directive can only mean that there are
  2904. two entries, 10 and -5.
  2905.  
  2906. In Inform 6 the other answer is true, because the parser always makes the
  2907. longest match it can.  Since this may mean that some Inform 5 code needs
  2908. changing in a few places, a warning that "this is ambiguous" is issued
  2909. for unbracketed minus signs used in array initialisations.
  2910.  
  2911. (Illustrating the problem further, if the user tries to clarify things with
  2912.  
  2913.     Array A --> 10 (-5);
  2914.  
  2915. then this is parsed under the normal rules as the function call 10(-5);
  2916. therefore another constant-context rule is used to interpret brackets as
  2917. always referring to subexpressions, not function calls.)
  2918.  
  2919.  
  2920. Similar difficulties at first seem to occur with < and >, and with << and >>. 
  2921. Does
  2922.  
  2923.     <Action 3 -4>
  2924.  
  2925. refer to the pair (Action, -1) or the triple (Action, 3, -4)?  (It is now
  2926. obvious that the correct syntax design would be to insist on a comma in
  2927. between 3 and -4.)   Fortunately, though, both Informs 5 and 6 apply a "make
  2928. the longest expression possible" principle to this case, so they agree that
  2929. the answer is (Action, -1).  On the same grounds, the statement
  2930.  
  2931.     <Action x ++ y>
  2932.  
  2933. is understood as applying ++ to x, not to y, because the "longest expression
  2934. possible" when parsing the first expression is "x ++".
  2935.  
  2936.  
  2937.     6.5   Constant folding
  2938.           ----------------
  2939.  
  2940. Recall that the emitter takes as input a stream of etokens from the
  2941. shift-reduce parser, consisting of the expression re-ordered into RPN.  When
  2942. the whole stream has been received (i.e., when it has received ENDEXP_TT),
  2943. the emitter has to produce an operand as "answer".
  2944.  
  2945. For instance, if the emitter receives just the operand 56, then the answer
  2946. is 56.  More often, the answer may be a special value (written above as E1,
  2947. E2, ...) meaning "the numerical value has to be worked out by working through
  2948. this tree".  (E1 is actually a new type of etoken, of type TREE_NODE_TT.)
  2949.  
  2950. If this were done strictly, then the original text 4 + 7 would result in the
  2951. emitter producing the answer E1, where E1 refers to the expression tree
  2952.  
  2953.                  +
  2954.                 / \
  2955.                4   7
  2956.  
  2957. and this is not a helpful answer, for two reasons: it means the value
  2958. couldn't be used as a constant (since it seems to need Z-code to compiled to
  2959. work it out), and even if it's used in code, there's not much point in
  2960. compiling the Z-code instruction
  2961.  
  2962.     @add 4 7 -> sp;
  2963.  
  2964. just to put the value 11 on the stack.
  2965.  
  2966. Therefore, if the emitter finds an operator that it knows how to calculate
  2967. (such as +), whose operands are all constants (and which are not unknown
  2968. for linking reasons), it eliminates the sub-expression in favour of the
  2969. result.  This is called "constant folding": the constant value 4+7 is
  2970. folded up into 11.
  2971.  
  2972. Two issues arise: firstly, arithmetic must be done exactly as it would be
  2973. done in the Z-machine, that is, as signed 16-bit arithmetic.  (Otherwise
  2974. constants may fold differently in one port of Inform or another.)
  2975.  
  2976. Secondly, constant folding cannot safely be performed on a marked value.
  2977. (For otherwise: consider what might happen to the expression SODS - LAW,
  2978. at a time when neither SODS nor LAW have been defined.  Both are evaluated
  2979. as constants with value their symbol numbers and marker SYMBOL_MV: the result
  2980. is folded to the difference between their symbol numbers, and the marker
  2981. is lost: i.e., the result is nonsense.)
  2982.  
  2983. The emitter is able to fold the following operators:
  2984.  
  2985.      +  - (unary or binary)   *  /  %  &  |  ~
  2986.      ==  ~=  >  <  >=  <=  &&  ||  ~~
  2987.  
  2988. The inclusion of the conditionals here is quite important: it enables
  2989. directives like
  2990.  
  2991.      Iftrue #version_number == 3;
  2992.  
  2993. to work, since the expression "#version_number == 3" can be parsed in a
  2994. constant context.
  2995.  
  2996. The inclusion of unary minus is also important, as it is only by folding
  2997. this that the text "-45" can be parsed in constant context.
  2998.  
  2999.  
  3000.     6.6   Checking lvalues and simplifying the parse tree
  3001.           -----------------------------------------------
  3002.  
  3003. If the emitter produces a parse tree, then it's now modified according to
  3004. several rules.  The aim is to remove any ambiguities in the tree (for
  3005. instance, "=" does several different things according to what its left
  3006. operand is) and make a final correctness check (for instance, this is where
  3007. "45 = 12" results in an error message).
  3008.  
  3009.  
  3010. Firstly, the tree is traversed to find instances where a value is used where
  3011. a condition was expected.  (If the expression is in a condition context, the
  3012. top node is expected to be a condition; the children of a logical operator
  3013. &&, || or ~~ are expected to be conditions.)  The configuration
  3014.  
  3015.           <value or tree>
  3016.  
  3017. is replaced by
  3018.  
  3019.       <~= 0 condition operator>
  3020.                  |
  3021.           <value of tree>
  3022.  
  3023. If the <value or tree> has root node the "=" operator, a warning is printed
  3024. out, since it seems likely that
  3025.  
  3026.     if (x = 4) ...
  3027.  
  3028. (which would invariably be found true, since the value of "x=4" is 4 which is
  3029. non-zero) is a mistype for
  3030.  
  3031.     if (x == 4) ...
  3032.  
  3033.  
  3034. A second, depth-first, traversal is then made to remove usages of ~~, using
  3035. de Morgan's laws:
  3036.  
  3037.             ~~(x && y)   =   ~~x || ~~y
  3038.             ~~(x || y)   =   ~~x && ~~y
  3039.             ~~(x == y)   =   x ~= y
  3040.             ~~(x >= y)   =   x < y
  3041.  
  3042. and so on.  (Note that, internally, every operator etoken has a corresponding
  3043. negated operator etoken.)
  3044.  
  3045.  
  3046. One ambiguity remaining in the tree is that the operators ".", ".#" and ".&"
  3047. act on both common and individual properties (that is, properties handled by
  3048. the Z-machine's architecture directly, and properties handled by the run-time
  3049. veneer routines).  The decision about which is intended is made here, by
  3050. looking at the right operands of the operators.  (If it's a common property
  3051. number, or an individual property number, the decision is obvious; if it's a
  3052. variable or some compound expression, then we decide in favour of individual
  3053. properties (the run-time veneer routines can patch things up if this is a
  3054. wrong decision).)
  3055.  
  3056. So a traversal is made to carry out the following transformation:
  3057.  
  3058.                .                             <common .>          <indiv .>
  3059.               / \             becomes          /    \      or      /   \
  3060.              a   b                            a      b            a     b
  3061.  
  3062. (Since the veneer routines are themselves written in Inform code, a slightly
  3063. different translation rule applies to them: "." always means <common .>
  3064. and so on, while three "secret" operators are provided, "..", "..&" and
  3065. "..#", to mean <indiv .> and so on.  Outside of the veneer, use of these
  3066. operators is illegal.)
  3067.  
  3068. In the same traversal, function calls are distinguished from sent messages:
  3069.  
  3070.              <fcall>                             <send message>
  3071.               /   \ \ ...                           / | | \ ...
  3072.        <common .>  c d        becomes              a  b c  d
  3073.       or <indiv .>
  3074.           / \
  3075.          a   b
  3076.  
  3077.  
  3078. The final traversal performs "lvalue checking".  Five operators act directly
  3079. on storage objects (such as variables) rather than values: these are
  3080.  
  3081.        <lvalue> = <ordinary value>
  3082.        <lvalue> ++
  3083.        <lvalue> --
  3084.        ++ <lvalue>
  3085.        -- <lvalue>
  3086.  
  3087. where <lvalue> has to be a reference to a storage object.  There are up to
  3088. five kinds of storage object in the tree:
  3089.  
  3090.        local/global variable                       VARIABLE_TT
  3091.        common property value of an object          <common .> subexpression
  3092.        individual property value of an object      <indiv .> subexpression
  3093.        entry in byte -> array                      -> subexpression
  3094.        entry in word --> array                     --> subexpression
  3095.  
  3096. This makes 25 combinations.  As well as checking that what ought to be an
  3097. lvalue is indeed one of these five possibilities, the traversal also
  3098. rewrites the tree explicitly with one of 25 operators.  For instance:
  3099.  
  3100.              =                                <set byte array entry =>
  3101.             / \                                    /    |    \
  3102.           ->   v        becomes                   a     b     v
  3103.          /  \
  3104.         a    b
  3105.  
  3106. and so on.
  3107.  
  3108. Thus, the end of this process is a tree representing a syntactically correct
  3109. expression (if necessary having mended any errors in the source code's
  3110. description of the expression), which has a minimal number of logical
  3111. operators and no negation operators, and in which the action to be taken by
  3112. any node does not depend on what its children are.
  3113.  
  3114.  
  3115.     6.7   Summary of parse tree output
  3116.           ----------------------------
  3117.  
  3118. It is time to formally specify the input and output of the main routine in
  3119. "expressp.c":
  3120.  
  3121.     assembly_operand parse_expression(int context)
  3122.  
  3123. takes, as argument, one of the seven *_CONTEXT constants:
  3124.  
  3125.           QUANTITY_CONTEXT    the default: the result may be any quantity
  3126.  
  3127.           VOID_CONTEXT        the expression is used as a statement, so that
  3128.                               its value will be thrown away and it only
  3129.                               needs to exist for any resulting side-effects
  3130.                               (used in function calls and assignments)
  3131.  
  3132.           CONDITION_CONTEXT   the result must be a condition
  3133.  
  3134.           CONSTANT_CONTEXT    the result must be known now (at compile time)
  3135.  
  3136.           ASSEMBLY_CONTEXT    like QUANTITY_CONTEXT, but with the '->'
  3137.                               operator forbidden
  3138.                               (this is needed for assembly language to
  3139.                               indicate store destinations)
  3140.  
  3141.           FORINIT_CONTEXT     like VOID_CONTEXT, but with the '::' operator
  3142.                               forbidden at the top level
  3143.                               (needed to resolve ambiguity in grammar)
  3144.  
  3145.           ARRAY_CONTEXT       like QUANTITY_CONTEXT, but with different rules
  3146.                               to resolve whether a minus sign represents
  3147.                               unary or binary minus
  3148.                               (needed to resolve ambiguity in grammar)
  3149.  
  3150. The return value is the result of the expression.  This is an assembly
  3151. operand, the type of which indicates what has happened:
  3152.  
  3153.           LONG_CONSTANT_OT, SHORT_CONSTANT_OT
  3154.                               the result is this number
  3155.  
  3156.           VARIABLE_OT         the result is in this global/local variable
  3157.  
  3158.           OMITTED_OT          there is no resulting value (for instance,
  3159.                               this happens if the expression was successfully
  3160.                               parsed in void context)
  3161.  
  3162.           EXPRESSION_OT       the result can only be determined by running
  3163.                               the code generated from this parse tree
  3164.  
  3165. If an error has occurred in the expression, from which recovery was not
  3166. possible, then the return is (short constant) 0.  This should minimise the
  3167. chance of a cascade of further error messages.
  3168.  
  3169. The type EXPRESSION_OT is not a valid Z-machine assembly operand type, and
  3170. it's only used here and in the code generator "expressc.c".  The value of
  3171. such an operand is an index N, indicating that the root node of the tree is
  3172. in Nth position in the expression-tree-array ET.
  3173.  
  3174. The expression-tree-array ET[0], ET[1], ... is an array of "nodes", each of
  3175. which is a structure as follows:
  3176.  
  3177.     {   /*  Data used in tree construction  */
  3178.  
  3179.         int up, down, right;
  3180.         int operator_number;         /* Only meaningful for non-leaves */
  3181.         assembly_operand value;      /* Only meaningful for leaves */
  3182.  
  3183.         /*  Attributes synthesised during code generation  */
  3184.  
  3185.         ...
  3186.  
  3187.     }
  3188.  
  3189. The numbers ET[n].up, ET[n].down and ET[n].right are node numbers for the node
  3190. above, the leftmost node below, and the next child to the right of the same
  3191. parent: they hold -1 if there is no node in that position.
  3192.  
  3193. A "leaf" is a node for which ET[n].down == -1.  Leaves hold operands, and
  3194. other nodes hold operators.  (Note that leaf operands must be of operand type
  3195. SHORT_CONSTANT_OT, LONG_CONSTANT_OT or VARIABLE_OT: they must be honest
  3196. Z-machine operands.)
  3197.  
  3198. Nothing distinguishes the root node except that its number happens to be held
  3199. in an EXPRESSION_OT operand value somewhere.
  3200.  
  3201.  
  3202. A brief word on deallocation: clearly these parse trees need to survive
  3203. intact until code generation occurs for them.  No elaborate system is provided
  3204. here, since the syntax analyser always generates code for any expressions it
  3205. reads while it's still parsing the same syntax line as the expression was
  3206. parsed on.  Each time a new syntax line is reached, "expressp.c" is notified
  3207. and it then wipes the ET[n] array empty again.
  3208.  
  3209.  
  3210.     7   Code generation from parse trees
  3211.         --------------------------------
  3212.  
  3213.     7.1   Aim and structure of the code generator
  3214.           ---------------------------------------
  3215.  
  3216. The section "expressc.c" takes as input a parse tree and generates suitable
  3217. Z-code to calculate the result of the expression which the parse tree
  3218. embodies.  As a result, its main output is a stream of function calls to
  3219. "asm.c" (see chapter 5 for details).
  3220.  
  3221. The syntax analyser calls only one routine:
  3222.  
  3223.    assembly_operand code_generate(assembly_operand AO, int context, int label)
  3224.  
  3225. where AO is expected to be the output from a previous run through "expressp.c".
  3226.  
  3227. The contexts are the same as those for expression parsing, except that only
  3228. VOID_CONTEXT, CONDITION_CONTEXT and QUANTITY_CONTEXT are allowed.
  3229.  
  3230. The "label" is only meaningful in CONDITION_CONTEXT:
  3231.  
  3232.     if label >= 0, branch to this label if the expression is false
  3233.         as a condition;
  3234.  
  3235.     if label == -3, rfalse if the expression is true;
  3236.  
  3237.     if label == -4, rtrue if the expression is true.
  3238.  
  3239. (Note that the presence of rfalse/rtrue here allows better code generation
  3240. for statements in the form
  3241.  
  3242.     if ( ... ) return;
  3243.  
  3244. owing to a feature of the Z-machine's architecture for branch instructions.)
  3245.  
  3246. The return AO is only meaningful in QUANTITY_CONTEXT; it holds the result
  3247. of the expression, often the stack pointer variable (meaning, the answer
  3248. is on the top of the stack) but not always: e.g., from
  3249.  
  3250.     j++, 2
  3251.  
  3252. the result would be SHORT_CONSTANT_OT 2.  Similarly, from the expression
  3253.  
  3254.     2
  3255.  
  3256. the code generator returns 2 without actually generating code.
  3257.  
  3258.  
  3259.     7.2   Annotation for conditions
  3260.           -------------------------
  3261.  
  3262. The first thing the code generator does is to "annotate" the tree for
  3263. conditions.  Annotation is the process of assigning useful values to
  3264. every node on the tree, usually in such a way that either the value at
  3265. one node determines the values for its children, or vice versa.  (Such
  3266. values are called "attributes" and this inductive definition of them
  3267. is called "synthesis": see ASU, p.280.)
  3268.  
  3269. The explanation of this algorithm is about five times longer than its
  3270. source code!
  3271.  
  3272. We wish to assign a pair of values written (on paper) in the form
  3273.  
  3274.     a | b
  3275.  
  3276. to every conditional node (that is, every node which is a conditional
  3277. operator such as "~=" or "ofclass", or is a logical operator such as "&&").
  3278. This is to be read as "branch to label a if true, or label b if false".
  3279. Inform has four special label numbers:
  3280.  
  3281.     -1 means "carry on rather than branch"
  3282.     -2 means "branch to the immediately following instruction" 
  3283.     -3 means "return false rather than branch"
  3284.     -4 means "return true rather than branch"
  3285.  
  3286. (-2 is used in the assembly of instructions like get_child_zc, which is
  3287. a conditional branch in Z-machine terms but which Inform wants to ignore
  3288. the branch result from.  We can ignore -2 here: it behaves exactly like
  3289. -1.)
  3290.  
  3291. One of the two numbers a and b must always be other than -1 (otherwise we
  3292. would have rendered a branch meaningless, which must be a mistake).  Ideally
  3293. exactly one of them is -1, so that the node can generate a single branch
  3294. instruction.
  3295.  
  3296. There are two points where these a | b attributes start to appear in the
  3297. tree.  Firstly, in condition context they'll appear at the root node: for
  3298. example, in CONDITION_CONTEXT with label 40 the top node would be labelled
  3299.  
  3300.                        -1 | 40
  3301.  
  3302. ("jump to L40 if false").  Secondly, at condition subexpressions used as
  3303. values, e.g. in the tree:
  3304.  
  3305.                           =
  3306.                          / \
  3307.                         v   ==
  3308.                            /  \
  3309.                           t    1
  3310.  
  3311. This is trickier: the result of == is not a branch somewhere, but a numerical
  3312. value (which must be 0 or 1).  To cope with such conversions, two more
  3313. attributes are provided:
  3314.  
  3315.     to_expression,  label_after
  3316.  
  3317. A node flagged as "to_expression" is one where a condition is being converted
  3318. to a numerical value; the "==" node above would have this flag set.
  3319.  
  3320. "label_after" is either -1 or the number of a label which the code generator
  3321. is to assemble after code generation for the node is complete.
  3322.  
  3323. So here are the rules for generating these attributes for node N.  Each node
  3324. is sent a pair of values a | b from its parent (in the case of the root
  3325. node, from the code_generate() routine).
  3326.  
  3327.     annotate N with
  3328.        a | b
  3329.  
  3330.     if N is &&, || or a conditional operator, and  a | b is -1 | -1,
  3331.     then this must be a condition used as a value:
  3332.     so re-annotate N with
  3333.        to_expression = TRUE
  3334.        label_after = a new label L
  3335.        L | -1
  3336.  
  3337.     if N is an && operator:
  3338.     a label for "go here if false" is going to be needed to provide a
  3339.     destination for the branch generated by the lefthand operand.  So,
  3340.     if b = -1, re-annotate N with:
  3341.        label_after = a new label L
  3342.        a | L
  3343.  
  3344.     if N is an || operator:
  3345.     a label for "go here if true" is going to be needed to provide a
  3346.     destination for the branch generated by the lefthand operand.  So,
  3347.     if a = -1, re-annotate N with:
  3348.        label_after = a new label L
  3349.        L | b
  3350.  
  3351.     Finally, we need to pass a pair of values down to each child of the
  3352.     node.  In the case of all nodes except && and ||, the values passed
  3353.     down are
  3354.  
  3355.          -1 | -1
  3356.  
  3357.     (because the operator expects numerical operands).
  3358.     
  3359.     In the case of && and ||, let x | y be the annotation which was finally
  3360.     made for this node.  We pass values down as follows:
  3361.     
  3362.                 &&                     ||
  3363.                /  \                   /  \
  3364.          -1 | y    x | y        x | -1    x | y
  3365.  
  3366. (Here "condition node" means a conditional or logical operator.  Recall that
  3367. the ~~ operator was eliminated earlier.)
  3368.  
  3369. For example, consider the condition in
  3370.  
  3371.     if (x == 1 || y >= 2) ...
  3372.  
  3373. The syntax analyser decides to generate code which will branch to L23 if the
  3374. condition is false.  The parse tree
  3375.  
  3376.                 ||                                       ||  -1 | 23, l_a = 50
  3377.                /  \                                       /    \
  3378.              ==    >=       is annotated to    == 50 | -1        >=  50 | 23
  3379.             /  \  /  \                            /      \        /      \
  3380.            x   1  y   2                          x        1      y        2
  3381.  
  3382. where the annotation routine created label 50 as a point to branch to if the
  3383. first condition turned out to be true.
  3384.  
  3385. Note that it's actually a little wasteful to annotate this way: the node >=
  3386. is annotated with 50 | 23, but label L50 will appear immediately after the
  3387. code generated for this node anyway, so it might as well be annotated -1 | 23.
  3388. The annotater does indeed make this simplification.
  3389.  
  3390.   Lemma: One of the values a, b sent down to any node is always -1.
  3391.  
  3392.   Proof: By induction down through the tree.  The values sent down to the
  3393.          root node are either -1 | L, -3 | -1 or -4 | -1, so the property
  3394.          holds for the root node.
  3395.          
  3396.          Now suppose such a pair a | b is sent down to node N.  Unless N is
  3397.          && or ||, it sends -1 | -1 to its children, so the property holds
  3398.          for the children of N.
  3399.  
  3400.          If N is &&, then it has two children, left and right.  The left
  3401.          child is always sent -1 | y, so it has the property.
  3402.  
  3403.          The right child is sent x | y, unless y is a new label appearing
  3404.          after N, in which case it is sent x | -1.  Note, though, that
  3405.          N itself was sent a pair in which one number was -1 (by inductive
  3406.          hypothesis) and so x | y can only have both numbers other than -1
  3407.          if a new label was created by N.  Since N is an && operator
  3408.          this label must be y; and therefore the child is sent x | -1,
  3409.          which means the right child also has the property.
  3410.  
  3411.          The argument for || is symmetrical to this.
  3412.  
  3413.   Corollary: In the annotation "a | b" of every node other than a && or ||
  3414.          operator, either a is -1 and b is not, or vice versa.
  3415.  
  3416. The annotation values a | b are only used to generate code for condition
  3417. operators, so we now have the desired result.
  3418.  
  3419.  
  3420.     7.3   Main traversal
  3421.           --------------
  3422.  
  3423. The main algorithm is simple.  We make a depth-first (i.e., bottom-up)
  3424. traversal of the parse tree, pruning off sub-expressions as code is
  3425. generated for them.  In the tree
  3426.  
  3427.                     *
  3428.                    / \
  3429.                   a   +
  3430.                      / \
  3431.                     b   c
  3432.  
  3433. we first descend to the +, and convert that into
  3434.  
  3435.     @add b c -> sp
  3436.  
  3437. and prune the tree to
  3438.  
  3439.                     *
  3440.                    / \
  3441.                   a   sp
  3442.  
  3443. so that the next instruction generated is
  3444.  
  3445.     @mul a sp -> sp
  3446.  
  3447. and the tree is now just
  3448.  
  3449.                     sp
  3450.  
  3451. and the result is therefore on the stack.  A complication, however, is what
  3452. order in which to remove the subexpressions.  Faced with the tree
  3453.  
  3454.                     -
  3455.                    / \
  3456.                   *   +
  3457.                  / \ / \
  3458.                 a  b c  d
  3459.  
  3460. do we go left first from the top -, or right first?  This decision is taken
  3461. for us by the Z-machine's architecture.  When the Z-machine executes the
  3462. instruction
  3463.  
  3464.     @sub sp sp -> x;
  3465.  
  3466. it takes the two operands off the stack in the order left to right, i.e.,
  3467. it pulls the first operand first and then the second.  (Most stack machines
  3468. work the other way, to make RPN expressions easy to evaluate.  The Z-machine
  3469. was designed for forward Polish notation, though, because Infocom's own
  3470. language for it was a Lisp-variant with syntax like (PLUS 2 3).)
  3471.  
  3472. This means that we need to push the second operand first, then the first
  3473. operand.  In other words, we have to code generate the + operation first,
  3474. and then the * operation.
  3475.  
  3476. Therefore we need to traverse the tree depth-first and right-to-left.
  3477. But there is a complication: the && and || nodes need to have their children
  3478. code-generated left-to-right.  (Although "and" is logically commutative,
  3479. so that it shouldn't matter, "&&" is not computationally commutative, because
  3480. the language specification requires that the left condition is never evaluated
  3481. if the right condition was false.)
  3482.  
  3483. There is one other left-to-right node: the comma operator.  For example,
  3484. if the original value of x is 10, then
  3485.  
  3486.                ,
  3487.               / \
  3488.             ++   x
  3489.             /
  3490.            x
  3491.  
  3492. must evaluate to 11, not 10, because "x++, x" must evaluate "x++" first,
  3493. throw the result away and then evaluate "x".
  3494.  
  3495.  
  3496.     7.4   Void context
  3497.           ------------
  3498.  
  3499. As the above example demonstrates, in some cases sub-expressions need to
  3500. produce a result and in other cases they must not do so.  If the "++" operator
  3501. had left a value on the stack, then it would still be there long after the
  3502. expression had been evaluated.
  3503.  
  3504. Therefore, when code generating each node it is essential to know where the
  3505. result of the expression is supposed to go.  A flag called void_flag is
  3506. passed down to indicate this: if set, then the operator is being evaluated
  3507. in "void context", meaning that the value should be thrown away.  The rules
  3508. are:
  3509.  
  3510.     if the expression is in VOID_CONTEXT, then the root node is;
  3511.     the left operand of a comma operator is in void context;
  3512.     if a comma operator is in void context, its right operand also is.
  3513.  
  3514. Not every subexpression is permitted to be in void context.  For instance,
  3515.  
  3516.     3*x, y++;
  3517.  
  3518. generates the error
  3519.  
  3520.     Result of expression is thrown away
  3521.  
  3522. because the * calculation was pointless.  Numerical values or variables are
  3523. not allowed in void context, and nor are any operators which have no "side
  3524. effect": i.e., whose evaluation causes nothing in the Z-machine to change.
  3525. The operators with side effects are:
  3526.  
  3527.     =  in its various forms (5 of them)
  3528.     ++ in its various forms (10 of them)
  3529.     -- in its various forms (10 of them)
  3530.     function call (including message sending)
  3531.  
  3532. It is only now, at code generation time, that the error message above is
  3533. generated.  (In C this would only cause a warning, but I didn't want to
  3534. waste effort making the code generator assemble code to explicitly throw
  3535. results away.)
  3536.  
  3537.  
  3538.     7.5   Results of subexpressions
  3539.           -------------------------
  3540.  
  3541. By the rules above, then, either an operator is in void context and its
  3542. result should be thrown away, or it isn't and the result should go onto the
  3543. stack.  However, this would be wasteful, as an expression like "x = 4 + y"
  3544. (where x is a local variable, say) would then generate
  3545.  
  3546.     @add 4 y -> sp
  3547.     @pull x
  3548.  
  3549. and give result "x".  In fact we want to generate
  3550.  
  3551.     @add 4 y -> x
  3552.  
  3553. and give the result "x".  Therefore, when code-generating an operator with
  3554. a result (such as @add), we look at the operator above (which is guaranteed
  3555. still to exist): if it is <set-variable-equal> then we get its left operand,
  3556. write the result of the operator (such as @add) to that, and replace the
  3557. <set-variable-equal> operator with the variable.  For instance,
  3558.  
  3559.         set-var-equal                               x
  3560.            /    \
  3561.           x      +           becomes just
  3562.                 / \
  3563.                4   y
  3564.  
  3565.  
  3566. One method used to throw away the results of expressions in void context
  3567. is to write the result to temporary variable 255 rather than the stack.
  3568. This is how unwanted function call return values are disposed of (well,
  3569. unless the Z-machine version number is 5 or more, in which case instructions
  3570. for call-but-throw-away-result are used directly).
  3571.  
  3572. A few other optimisations are used in void context: for example,
  3573.  
  3574.          ++ used as postfix on variable
  3575.                        |
  3576.                       var
  3577.  
  3578. generates the code
  3579.  
  3580.     @push var
  3581.     @inc var
  3582.  
  3583. with result "sp" in a quantity context.  In void context, it generates
  3584. simply
  3585.  
  3586.     @inc var
  3587.  
  3588. This is quite an important optimisation since postfix-++ is used very often
  3589. in void context (in "for" statements and just as an assignment).
  3590.  
  3591.  
  3592.     7.6   Conditional and logical operators
  3593.           ---------------------------------
  3594.  
  3595. The above account covers code generation for arithmetic and assignment
  3596. operators.
  3597.  
  3598. In generating && and ||, nothing needs to be done except possibly to
  3599. assemble a label (if the attribute label_after isn't -1).
  3600.  
  3601. Generating for conditions like == is in principle easy but in practice
  3602. difficult.  Recall that we have three attributes to go on:
  3603.  
  3604.     a | b              labels to branch to on true | false,
  3605.                            one which is -1 meaning "carry on"
  3606.     to_expression      flag indicating "convert to numerical value"
  3607.  
  3608. One problem is that, because of the "or" operator, a condition like ==
  3609. may have an arbitrary number of children:
  3610.  
  3611.     if (x == a or b or c or d or e) ...
  3612.  
  3613. for instance, must be assembled into the instructions:
  3614.  
  3615.     @je x a b c ?L2
  3616.     @je x d e ?~L1
  3617.     .L2
  3618.          ...
  3619.     .L1
  3620.  
  3621. (and if x is a use of the stack pointer, it must be pulled into some temporary
  3622. variable so that it can be non-destructively read more than once).  The code
  3623. to achieve this is baroque but uninteresting.
  3624.  
  3625. The second question is how to convert a condition to a numerical value:
  3626. either 0 (false) or 1 (true).  At present, this is not very optimised, and
  3627. the code looks like:
  3628.  
  3629.     <if condition is true jump to L1>
  3630.     @push 0
  3631.     @jump L2
  3632.     .L1
  3633.     @push 1
  3634.     @jump L2
  3635.  
  3636. with the result being "sp".
  3637.  
  3638.  
  3639.     7.7   System functions
  3640.           ----------------
  3641.  
  3642. When generating the <function call> operator, Inform looks at the leftmost
  3643. operand (the function to call) to see if it's the name of a system function.
  3644. (Note that if the system function has been Replaced, then it will have been
  3645. filtered out long since and the name will have been treated as the symbol
  3646. name for a function in the usual way.)
  3647.  
  3648. These are all implemented as short inline functions (sometimes only one
  3649. instruction long) except for "metaclass", implemented as a veneer routine.
  3650.  
  3651. Note that
  3652.  
  3653.              random
  3654.              / | |
  3655.             a  b c ....
  3656.  
  3657. nodes are generated by creating a word array whose contents are a, b, c, ...
  3658. and then assembling code to read a random entry from this array.  (An
  3659. error is issued if a, b, c, etc. are found not to be constant values.)
  3660.  
  3661.  
  3662.     8   Assembly of code, text and data structures
  3663.         ------------------------------------------
  3664.  
  3665.     8.1   Assembly of initial code
  3666.           ------------------------
  3667.  
  3668. The front end of "asm.c" consists of three routines to assemble routine
  3669. start and finish, and to place labels; plus many routines for assembling
  3670. individual instructions.  These all fill out data in the
  3671. assembly_instruction AI and then call a single assemble-instruction routine.
  3672. Thus, the back end of "asm.c" contains four operations to place data into
  3673. the Z-machine's code area:
  3674.  
  3675.     Routine start           assemble_routine_header()
  3676.     Routine end             assemble_routine_end()
  3677.     Label                   assemble_label_no()
  3678.     Instruction             assemble_instruction()
  3679.  
  3680. For the format of Z-code instructions, see the Z-Machine Standard Document,
  3681. which goes into the Z-machine's format with exhaustive thoroughness.  Note
  3682. that Inform 6 is much more compliant to the standard (so far as I know,
  3683. perfectly compliant) than earlier releases: for example, the Flags 2 bits
  3684. for "UNDO is needed" and so on are set correctly for the first time.
  3685.  
  3686. One of the few pieces of information fed back to Inform's higher levels by
  3687. "asm.c" is a flag indicating whether execution can possibly reach the next
  3688. instruction or not.  The assembly of certain instructions (returning from
  3689. a routine, terminating the Z-machine, unconditionally jumping) sets the
  3690. flag
  3691.  
  3692.     execution_never_reaches_here
  3693.  
  3694. while the placing of a label removes it again (because by branching to that
  3695. label it may be possible to reach this point after all).  This is used to
  3696. issue dead code warnings (and also to remove some unnecessary branches
  3697. when code-generating "if"..."else"...).
  3698.  
  3699. Assembling a routine header is straightforward: note that an option exists
  3700. here to assemble some code along with it to print out tracing information.
  3701. For this reason, and also to print out assembly trace at compile time,
  3702. "asm.c" accesses the variable names in the symbols table.
  3703.  
  3704. All labels are referred to in Inform's higher layers by number, rather than
  3705. by address; only "asm.c" has any access to what their addresses are.  Labels
  3706. are numbered from 0 upwards, but the assembler also recognises
  3707.  
  3708.     -2    branch only to the next instruction (this converts a branch
  3709.           instruction such as @get_child to a non-branch one, since it
  3710.           causes the instruction to behave identically whether the branch
  3711.           is made or not)
  3712.     -3    return false rather than branch
  3713.     -4    return true rather than branch
  3714.  
  3715. The code -1, used higher up for "no branch intended", should never descend
  3716. this far.
  3717.  
  3718. Note that the Z-machine has no formal concept of "routine end".  Therefore,
  3719. assemble_routine_end() only generates code to cause a return (and only then
  3720. if the present instruction position can be reached).  By long-standing
  3721. (if unfortunate) Inform convention, the value returned in this case will
  3722. be 0 for a routine in an object definition, or 1 for any other routine.
  3723.  
  3724. The routine-start/end routines also keep track of the usage of local
  3725. variables and labels, and issue warnings about those which were declared
  3726. but not used.  Since the scope of these symbols is restricted to the routine
  3727. in which they are defined, label names are unassigned (i.e. reset to
  3728. UNKNOWN_SFLAG CONSTANT_T's).  Local variable names are not held in the
  3729. symbols table and are automatically cleared when the next routine starts.
  3730. Finally, we can now detect the use of a label name not defined in the routine,
  3731. so we issue an error message if this has happened.
  3732.  
  3733.  
  3734. What happens in this first phase of code assembly is that a form of Z-code
  3735. called "initial code" is stored in a temporary holding area of memory until
  3736. a routine has been completed.  It is then treated by the branch optimiser
  3737. (see the next section).
  3738.  
  3739. "Initial code" is the same as Z-code, except that:
  3740.  
  3741.     (a)  all branches to labels have long form, and instead of an offset
  3742.          the branch value is the label number within this routine
  3743.          (0, 1, 2, ...);
  3744.     (b)  LABEL operands (to "jump" instructions) are, similarly, label
  3745.          numbers of the label to branch to;
  3746.     (c)  parallel to the holding area is a uchar[] buffer of the same size,
  3747.          holding a "marker value" for each byte.
  3748.  
  3749. (Note that branches to -2, -3 and -4 are assembled as short-form branches
  3750. and not marked as BRANCH_MV.)  The marker values are as follows:
  3751.  
  3752.     BRANCH_MV        This byte is the first of two in a branch operand
  3753.     LABEL_MV         Ditto but in a LABEL operand
  3754.     DELETED_MV       (Inserted by the optimiser, rather than at initial
  3755.                      code assembly.)  This byte has been deleted and should
  3756.                      be skipped over when the code is transferred to
  3757.                      long-term storage.
  3758.     a "module value" marker value
  3759.                      This byte is the first of two in a LONG_CONSTANT_OT
  3760.                      operand which should be marked with this value in
  3761.                      module compilation
  3762.     ditto + 128      Ditto but a one-byte SHORT_CONSTANT_OT or VARIABLE_OT
  3763.                      operand
  3764.  
  3765.  
  3766.     8.2   Branch offset backpatching and optimisation
  3767.           -------------------------------------------
  3768.  
  3769. There are three phases of this process:
  3770.  
  3771.     (i)   Deciding whether each branch should or should not be optimised
  3772.           to the 1-byte short form, using the label positions in the
  3773.           initial code;
  3774.     (ii)  Recalculating the label positions to take account of this
  3775.           (which will tend to move the labels closer together as second
  3776.           bytes of branch operands are deleted);
  3777.     (iii) Transferring the initial code to long-term storage, replacing
  3778.           branch and LABEL operand values with address offsets and
  3779.           issuing module markers as indicated (if in module mode).
  3780.  
  3781. A branch can be "short form" if it is a forward branch of between 0 and 29
  3782. bytes from the PC position of the next instruction.          
  3783.  
  3784. To record a branch as "short form" during (i), the second byte of the branch
  3785. operand is marked as DELETED_MV.
  3786.  
  3787. The long-term storage alluded to is either temporary file 2 or else the
  3788. zcode_area memory block.  Note that the routines moved there are still not
  3789. finally correct, but are "raw Z-code": Z-code which has incorrect operands
  3790. because value backpatching has not yet occurred.
  3791.  
  3792.  
  3793.     8.3   Text translation: ISO and Unicode resolution
  3794.           --------------------------------------------
  3795.  
  3796. The algorithm encoding ZSCII text to a compressed sequence of 5-bit
  3797. "Z-characters" has been documented many times: see the Z-machine standards
  3798. document.  
  3799.  
  3800. The section of Inform responsible, "text.c", keeps text for three Z-machine
  3801. areas: the static strings area, the dictionary and the "low strings pool".
  3802. (In addition, as requested by "asm.c", it encodes text into the Z-code area
  3803. as part of the assembly instructions @print and @print_ret.)
  3804.  
  3805. Static strings are written to a temporary holding area of memory, manipulated
  3806. until correct and then transferred to long-term storage: either temporary
  3807. file 1 or the static_strings_area memory block.
  3808.  
  3809. The low strings pool holds a table of strings in low Z-machine memory used
  3810. for abbreviations.  Such strings need to be accessible in an unusual way
  3811. (they are addressed by halved byte addresses, not packed addresses) owing
  3812. to an anomaly in the Z-machine architecture, and therefore must reside in
  3813. the bottom 64K of memory: they cannot be written to the static strings area.
  3814.  
  3815.  
  3816. Source text arrives at the text translation routines still encoded in an
  3817. ISO extension to the ASCII character set (depending on the current value
  3818. of the -C switch).  A character value of $ca might mean Latin E-circumflex,
  3819. E-ogonek, Cyrillic capital hard-sign, Arabic Teh or Greek capital Kappa
  3820. according to this context.  It would be illegal in plain ASCII or ISO
  3821. Hebrew, but since the Inform lexer has already filtered out any illegal
  3822. ISO characters, this possibility no longer arises.
  3823.  
  3824. Furthermore, characters can be specified by string escapes beginning with
  3825. the @ character.  The sequence @^E would specify Latin E-circumflex, and
  3826. the sequence @{39A} would specify Greek capital Kappa (by its Unicode
  3827. value, $039A) regardless of the current -C setting.
  3828.  
  3829. The work of sorting out character codes is handled by "chars.c".  It may
  3830. be useful to summarise the different meanings which character codes can
  3831. hold within Inform:
  3832.  
  3833.   (1)  "Source".  Raw source files can contain any character values
  3834.        between $00 and $ff.  The lexer filters these characters to reduce
  3835.        them to:
  3836.  
  3837.   (2)  "ISO".  An unsigned 8-bit character code within which the values
  3838.        $20 to $7e always have their usual ASCII meanings, and $7f to $9f
  3839.        are always undefined, and some values in the range $a0 to $ff
  3840.        may have meanings as specified in ISO 8859-1 to -9 if the current
  3841.        Inform -C setting is 1 to 9.  If -C is set to 0, "ISO" means the
  3842.        same as plain ASCII.
  3843.  
  3844.   (3)  "Unicode".  Unicode, or ISO 10646-1, is an unsigned 16-bit
  3845.        character code which includes essentially every human script.
  3846.        Inform uses it as an intermediate state between the diverse
  3847.        ISO possibilities and the final ZSCII result.
  3848.  
  3849.   (4)  "Text".  A string of ISO characters to specify a sequence of one
  3850.        or more Unicode characters.  Usually, one ISO character is
  3851.        translated to one Unicode character: the exception is for string
  3852.        escapes.  For instance, the text "a@{39a}c" specifies a sequence
  3853.        of 3 Unicode characters.
  3854.  
  3855.   (5)  "ZSCII".  An unsigned 10-bit character code used within the
  3856.        Z-machine.  See the Standards document for its definition: note
  3857.        that between $20 and $7e, it agrees with ASCII.
  3858.  
  3859.   
  3860. There are several translation routines in "chars.c" to move between these
  3861. forms: for instance, "zscii_to_text" is used when printing out the
  3862. contents of the dictionary into a transcript file.  (Transcript files
  3863. use the same ISO setting as the original source code.)  However, the
  3864. main sequence of translation is:
  3865.  
  3866.        Source -------> Text -------> Unicode -------> ZSCII
  3867.               lexer         ISO-to-          Unicode-to-
  3868.               filtration    Unicode;         ZSCII
  3869.                             string escape
  3870.                             parsing
  3871.  
  3872. Note that the first two stages (lexer filtration and ISO to Unicode)
  3873. depend only on the current -C setting, and are always possible.  The
  3874. third stage (Unicode to ZSCII) is more complex because it is programmable
  3875. and may fail, depending on what the text is needed for.
  3876.  
  3877. Unicode already specifies over 30000 different characters and
  3878. compromise is inevitable in trying to squash this into the 1024 possible
  3879. ZSCII values.  The Z-machine's stock of "extra characters"
  3880. (see Standard Document 1.0) is configured by the story file to
  3881. correspond to a block of up to 97 Unicode characters, and these
  3882. are the only ones usable in Inform strings, dictionary words or
  3883. as quoted values.
  3884.  
  3885. Inform sets up this block to a sensible default set given the
  3886. current ISO setting.  For example, if Inform reads in source code under
  3887. -C6 (ISO Arabic) then it will choose all the Arabic letters from
  3888. ISO Arabic.  (This default setting can be overridden using the
  3889. "Zcharacter" directive.)  Note that if the designer wants, say,
  3890. Unicode $274b ("heavy eight teardrop-spoked propeller asterisk")
  3891. as well as plain old $0621 (Arabic letter Hamza), this can simply
  3892. be added to the stock accumulated so far.
  3893.  
  3894. The stock of extra characters is defined by a list of Unicode values
  3895. written out as the "Unicode translation table" in "tables.c".
  3896.  
  3897.  
  3898.     8.4   Dictionary management
  3899.           ---------------------
  3900.  
  3901. As dictionary words are found in the source code, for instance in the value
  3902. of "name" properties, or in grammar, or in constants like 'this', they are
  3903. added to the dictionary by a routine called dictionary_add(), which numbers
  3904. each different word in "accession order": word 0 is the first which was
  3905. entered, and so on.
  3906.  
  3907. References to dictionary words are actually stored in the Z-machine as
  3908. byte addresses within the dictionary table, which cannot be known until after
  3909. the compilation pass (when the full alphabetical ordering is known).  Such
  3910. references are therefore always marked (with DICT_MV) for backpatching.
  3911.  
  3912. During compilation a dictionary table similar to the Z-machine format is
  3913. kept: there is a 7-byte header (left blank here to be filled in at the
  3914. construct_storyfile() stage in "tables.c") and then a sequence of records,
  3915. one per word, in the form
  3916.  
  3917.         <Z-coded text>    <dict_par1>  <dict_par2>  <dict_par3>
  3918.         4 or 6 bytes       byte         byte         byte
  3919.  
  3920. The difference between this and the final Z-machine dictionary table is
  3921. that the records occur in accession order, not alphabetical order.  (The
  3922. construct_storyfile() routine in "tables.c" rearranges them.)
  3923.  
  3924. The Z-machine does not specify what use is made of the three bytes of
  3925. "dictionary parameters" (it doesn't even specify that there have to be only
  3926. three): for this, see the next section.
  3927.  
  3928.  
  3929. The type "dict_word" is used for a structure containing the (4 or) 6 bytes of
  3930. Z-coded text of a word.  Usefully, because the PAD character 5 is < all
  3931. alphabetic characters, alphabetic order corresponds to numeric order of
  3932. Z-encoding (regarding the Z-encoded bytes as a 32 or 48 bit big-end-first
  3933. number; sign is unimportant as the initial bit is never set).  For this
  3934. reason, the dict_word is called the "sort code" of the original text word.
  3935.  
  3936. A special text-translation routine is used to "prepare" such a sort code:
  3937. as dictionary words do not use every feature possible in ordinary text
  3938. translation (abbreviations, for instance, or two of the string escape
  3939. forms) it's worth having a separate routine, optimised for speed.  Note
  3940. that this routine makes use of "text_to_unicode" and "unicode_to_zscii"
  3941. in "chars.c" when, but only when, it hits a string escape character @.
  3942. (For ordinary ISO characters, when no string escape is hit, these routines
  3943. would be too slow.)
  3944.  
  3945.  
  3946. Since dictionaries typically contain 500 to 2000 words, speed is extremely
  3947. important when searching and sorting: a simple O(n^2) algorithm to search the
  3948. dictionary, for example, greatly increases Inform's total compilation time on
  3949. medium-size games.  (Here "n" is the number of dictionary words.)
  3950.  
  3951. Inform 1 to 3 used a crude O(n^2) mass comparison algorithm, which was
  3952. unacceptably slow.  Inform 4 to 6.05 used a form of hash table, with the
  3953. first character of a word as hash function (there were 27 hash values, for
  3954. A to Z plus "other"): this behaved very acceptably most of the time, but was
  3955. ultimately still O(n^2) and the uneven distribution of initial letters in
  3956. English meant that the hashing function was not ideal.
  3957.  
  3958. Inform 6.1 instead stores the dictionary as a "red-black tree".  (See, e.g.,
  3959. Robert Sedgewick, "Algorithms" (1983, second ed. 1988).)  The tree is binary
  3960. and always has the property that at node X, anything hanging from the left
  3961. branch of X is alphabetically before what's at X, and anything hanging from
  3962. the right is alphabetically after.  For instance, a legal configuration is:
  3963.  
  3964.                              fieldmouse
  3965.                                /    \
  3966.                           abacus   patrician
  3967.                           /   \
  3968.                          a    constantinople
  3969.  
  3970. This is simple enough to build and to search through.  The problem is that
  3971. one usually ends up with a haphazardly arranged or "unbalanced" tree in which
  3972. some branches are very much longer than others, so that searching times can be
  3973. unpredictable, and in worst case the construction process is still O(n^2).
  3974.  
  3975. Thus one wants a method of building the tree which attempts to restore the
  3976. balance as it does so.  The algorithm here involves "colouring" each branch
  3977. either red or black (that is, storing one bit of information for each branch).
  3978. Roughly speaking, suppose X is added as a branch of Y.  Then the branch
  3979. leading down from Y to X -- the new branch -- is coloured black.  But the
  3980. branch leading down to Y -- which was already there -- is recoloured red.
  3981.  
  3982. We do not permit the tree to contain two consecutive red branches: whenever
  3983. we notice this happening, we perform a "rotation".  A typical rotation is:
  3984.  
  3985.                   a                        a
  3986.                    \                        \
  3987.                     bag                      cat
  3988.                    / \(red)    --->     (red)/ \(red)
  3989.                  baa cat                  bag   dog
  3990.                      / \(red)            /  \
  3991.                    bun   dog           baa  bun
  3992.  
  3993. It's like lifting the "bag" subtree and re-hanging it from the word "cat".
  3994. (There is another case, when the red branches slope in opposite directions.)
  3995.  
  3996. We also try to percolate redness upwards (redness being the possibility for
  3997. change in the tree structure).  So, when searching, if we ever find
  3998.  
  3999.                  \(black)
  4000.                    node
  4001.              (red)/    \(red)
  4002.  
  4003. then we replace it with
  4004.  
  4005.                  \(red)
  4006.                    node
  4007.            (black)/    \(black)
  4008.  
  4009. and check the "rotate if you get two consecutive red branches" rule again.
  4010.  
  4011. It is known that:
  4012. (i)  if there are N words in the tree, then any search takes less than
  4013.      2 log-to-base-2(N) + 2 comparisons (i.e., this is the maximum depth
  4014.      of the tree);
  4015. (ii) at worst you need to perform only one rotation for every four
  4016.      comparisons.
  4017. In practice, the observed values are even better: the average seems to
  4018. be log-to-base-2(N) comparisons and 1 rotation (though this is unproven).
  4019. Trees are almost optimally balanced most of the time.
  4020.  
  4021. For an Inform game with a dictionary of 2000 words, then, we expect to perform
  4022. about 12 comparisons per search.  This compares with a typical figure of 75
  4023. using the Inform 6.05 hashing algorithm.  Comparisons are not terribly
  4024. expensive, but searches are quite frequent.
  4025.  
  4026.  
  4027.  
  4028.     8.5   Format of tables unspecified by the Z-machine
  4029.           ---------------------------------------------
  4030.  
  4031. The Z-machine standards document requires many tables to have particular
  4032. formats and locations: but Inform makes several other tables, and this
  4033. section is to document their formats.  (See the construct_storyfile()
  4034. routine in "tables.c" for exactly how the byte-addressable Z-machine memory
  4035. is put together.)
  4036.  
  4037. Details of differences in modules as compared with story files are given
  4038. later.
  4039.  
  4040.     (i)  Header
  4041.  
  4042. Following standard conventions, Inform: leaves bits 2 and 3 of "Flags 1"
  4043. clear; places the release number in the word at bytes 2 and 3; the grammar
  4044. table address at bytes 14 and 15; and the serial number in bytes 18 to 23. 
  4045. The default release number is 1 and the default serial number is either
  4046. 970000 (if no access to the current date is available) or the compilation
  4047. date in the form YYMMDD.
  4048.  
  4049. In addition, Inform writes its version number in ASCII form into bytes
  4050. 60 to 63 (the last four bytes of the header) in the form "6.01".  This
  4051. makes story files produced by Inform 6 distinguishable from all other
  4052. story files, something interpreter writers have long wanted.
  4053.  
  4054.     (ii)  Low strings pool and abbreviations table
  4055.     
  4056. By default, the 96 entries are all "   " (this Z-encodes to the $80 $00,
  4057. which makes it a convenient default value).  The first two banks of 32
  4058. are used for strings declared by Abbreviate; the third is set at run time
  4059. by the "string" statement, to values which have previously been declared
  4060. by Low_string.
  4061.  
  4062. The pool of low strings is always placed at $0040, immediately after the
  4063. header and before the abbreviations table.
  4064.  
  4065.     (iii)  Header extension table
  4066.  
  4067. The Z-machine standard allows games not to provide a header extension
  4068. table (formally called the "mouse data table" after the only information
  4069. which Infocom ever stored in it) and Inform 6.01 to 6.11 never do.
  4070. Inform 6.12 and later always generate this extension, which always
  4071. contains at least 3 word entries.
  4072.  
  4073.     (iv)  Character set table
  4074.  
  4075. This is a table of 78 = 3*26 bytes, giving the Z-character numbers of
  4076. the characters to appear in the three translation alphabets.  The table
  4077. is only written if the "Zcharacter" directive has been used to alter
  4078. the standard settings.  (See section 12.2.)
  4079.  
  4080.     (v)  Unicode translation table
  4081.  
  4082. This is generated (by Inform 6.12 and later) only when needed, i.e., only
  4083. when a game has asked to use a stock of "extended characters" which
  4084. differs from the usual ISO Latin1 set.  Games compiled under the ISO
  4085. setting -C0, -C1 (the default setting) and -C9 will usually never
  4086. have a Unicode translation table, though they can have.
  4087.  
  4088.     (vi)  Property default values table
  4089.  
  4090. Note that Inform defines properties 1, 2 and 3 automatically: 1 is "name",
  4091. while 2 and 3 are used to support the veneer routines' implementation of
  4092. object orientation.
  4093.  
  4094.     (vii)  Class-number-to-object-number table
  4095.     (viii)  Individual property values table
  4096.  
  4097. See the notes on object orientation; these tables are used by the veneer
  4098. and are unspecified by the Z-machine.
  4099.  
  4100.     (ix)  Grammar table
  4101.     (x)  Actions table
  4102.     (xi)  "Preactions" table
  4103.     (xii)   "Adjectives" table
  4104.  
  4105. See the next section.  The Z-machine specifies none of these tables.
  4106.  
  4107.     (xiii)   Dictionary table
  4108.  
  4109. The format of this table is largely specified by the Z-machine.  Although
  4110. the Z-machine allows some flexibility in setting up the dictionary, Inform
  4111. sticks to the usual Infocom configuration:
  4112.  
  4113.     the separating characters are full stop, comma and space;
  4114.     the word-entry length is 7 (in version 3) or 9 (otherwise).
  4115.  
  4116. Thus the dictionary begins with seven header bytes:
  4117.  
  4118.     3  '.'  ','  ' '  7-or-9  <word containing the number of entries>
  4119.  
  4120. Each word is encoded with an entry giving 4 (in version 3) or 6 (otherwise)
  4121. bytes of textual representation, fully specified by the Z-machine, and
  4122. then three bytes of data, which Inform can do with as it pleases.
  4123.  
  4124. These are the so-called "dictionary parameters" dict_par1, 2 and 3.  Inform's
  4125. pleasure is to write into them as follows:
  4126.  
  4127.     dict_par1: flags
  4128.     dict_par2: verb number (counting downwards from 255)
  4129.     dict_par3: preposition number (counting downwards from 255) in
  4130.                grammar version 1; not used in grammar version 2
  4131.  
  4132. The flags are given as follows:
  4133.  
  4134.     bit:    7      6   5   4   3     2        1      0
  4135.             <noun>             <adj> <plural> <meta> <verb>
  4136.  
  4137. The bits <verb>, <noun> and <adj> are set if the word can be used in the
  4138. context of a verb, noun and/or preposition (all three can be simultaneously
  4139. set).  The <meta> bit indicates that the English verb is "meta", that is,
  4140. is a command to the program and not a request in the game.
  4141.  
  4142. The <plural> bit is set using the '...//p' notation, like so:
  4143.  
  4144.     'egg'  'eggs//p'
  4145.  
  4146. Library 6/3's parser uses this to automatically detect commands referring
  4147. to multiple game objects.
  4148.  
  4149.     (xiv)  Module map
  4150.  
  4151. This is an extension to the header, only used in module files (see later).
  4152.  
  4153.     (xv)  Linking data table
  4154.  
  4155. A table placed after the end of static strings, but only in module files
  4156. (see later).
  4157.  
  4158. To summarise, then, an Inform game has the following memory map:
  4159.  
  4160.       -----------------------------------------------------------
  4161.       Dynamic      Header
  4162.        memory      Low strings pool
  4163.                    Abbreviations table
  4164.                    Header extension                   
  4165.                    Character set table (if differs from normal)
  4166.                    Unicode table (if differs from normal)
  4167.                    Common property default values                  (*)
  4168.                    Object tree
  4169.                    Common property value tables                    (*)
  4170.                    Class number to object number conversion table
  4171.                    Property names table                            (+)
  4172.                    Individual property value tables                (*)
  4173.                    Global variable values, part of...              (*)
  4174.                    ...Dynamic array space                          (*)
  4175.       -----------------------------------------------------------
  4176.       Static       Table of grammar table addresses
  4177.       byte         The grammar tables (one for each Inform verb)   (-)
  4178.       addressed    Table of action routine addresses               (+)
  4179.       memory       Table of parsing routine addresses              (+)
  4180.                    Table of "adjectives", i.e., prepositions       (+)
  4181.                    Dictionary
  4182.                    (Module map)
  4183.                    Synchronising gap of up to 7 null bytes
  4184.       -----------------------------------------------------------
  4185.       Static       Z-code area                                     (*)
  4186.       "virtual"    Static strings area
  4187.       memory       (Link data table)
  4188.       -----------------------------------------------------------
  4189.       (*)  This area requires full value backpatching
  4190.       (+)  This area requires a simple automatic correction
  4191.            (e.g. adding on the static strings or code offsets),
  4192.            which is done without the full backpatching machinery
  4193.       (-)  In grammar version 1, this area requires no backpatching,
  4194.            but in GV2 each grammar token's data is checked to see
  4195.            if a dictionary word or routine address, and backpatched
  4196.            if so: so in GV2 it comes under category (+)
  4197.  
  4198.  
  4199.     8.6   Grammar version numbers GV1 and GV2
  4200.           -----------------------------------
  4201.  
  4202. The "grammar tables", used by the parser in an adventure game, are not
  4203. specified by the Z-machine at all (contrary to popular opinion) and must
  4204. therefore be fully specified here.  There are four such tables:
  4205.  
  4206.     Grammar table
  4207.     Actions table
  4208.     "Preactions" table
  4209.     "Adjectives" table
  4210.  
  4211. Inform can generate two different formats for these tables, known as
  4212. grammar version 1 (henceforth GV1) and grammar version 2 (GV2).
  4213.  
  4214. Inform makes the GV1 or GV2 decision according to the value of the symbol
  4215.  
  4216.     Grammar__Version
  4217.  
  4218. which Inform usually defines as 1, but allows programs to redefine.  Library
  4219. 6/3 and later, in particular, contain the line
  4220.  
  4221.     Constant Grammar__Version = 2;
  4222.  
  4223. Note that it is essential for the library's parser to understand the
  4224. grammar tables being generated by Inform, so attempting to use GV2 with
  4225. library 6/2 or earlier would fail.
  4226.  
  4227.  
  4228. The designs of GV1 and GV2 have some points in common.  The Grammar table
  4229. is a --> array containing addresses of grammars, one for each Inform verb.
  4230. The Actions table is a --> array containing addresses of action routines
  4231. (such as "TakeSub"), one for each action.  (Fake actions have no action
  4232. routines and aren't in the table.)
  4233.  
  4234. (The term "Inform verb" means essentially a common parsing grammar, such as
  4235. that shared by "take" and "hold", and is used to distinguish this from an
  4236. "English verb", such as the word "take".)
  4237.  
  4238.  
  4239. GV1 is at heart an imitation of middle-period Infocom table formats, and
  4240. was used in order that common debugging tools would still work on Inform
  4241. games (an important consideration in the early days of debugging Inform 1).
  4242. In GV1, an individual grammar table has the format:
  4243.  
  4244.     <number of grammar lines>          1 byte
  4245.  
  4246. followed by that many 8-byte lines in the form:
  4247.  
  4248.     <parameter count>  <token1> ... <token6>  <action number>
  4249.     -- byte ---------  --byte--     --byte--  -- byte -------
  4250.  
  4251. The parameter count is the number of tokens which are not prepositions.
  4252. This is needed because the run of tokens is terminated by null bytes (00),
  4253. which is ambiguous: "noun" tokens are also encoded as 00.
  4254.  
  4255. The numerical token values are as follows:
  4256.  
  4257.     "noun"            0  
  4258.     "held"            1  
  4259.     "multi"           2  
  4260.     "multiheld"       3  
  4261.     "multiexcept"     4  
  4262.     "multiinside"     5  
  4263.     "creature"        6  
  4264.     "special"         7  
  4265.     "number"          8
  4266.     noun=Routine      16 + parsing-routine-number
  4267.     Routine           48 + parsing-routine-number
  4268.     scope=Routine     80 + parsing-routine-number
  4269.     attribute         128 + attribute number
  4270.     'preposition'     adjective number
  4271.  
  4272.     illegal values:   9-15, 112-127
  4273.  
  4274. This one-byte value has to identify particular prepositions and routines,
  4275. which is only possible using a numbering system for each.  GV1 numbers
  4276. parsing-routines upwards from 0 to 31, in order of first use.  A separate
  4277. table translates these into routine packed addresses: the "preactions"
  4278. table.  (As usual, the term is traditional: Inform has no concept of
  4279. preaction, but the Infocom games from which it inherits GV1 do have such a
  4280. concept.)  The preactions table is a simple --> array.
  4281.  
  4282. (Note that in Infocom's games the preactions table always has the same
  4283. length as the actions table: this is not true in either GV1 or GV2 Inform
  4284. games.)
  4285.  
  4286. Prepositions are also identified by their "adjective number".  (An early
  4287. misunderstanding in Z-machine decipherment led to the traditional use of
  4288. the word "adjective" for dictionary words explicitly written into grammar
  4289. lines, which are mainly prepositions like 'into' or 'against'.)  Adjective
  4290. numbers count downwards from 255 in order of first use.  They are translated
  4291. back into dictionary words using the "adjectives table".
  4292.  
  4293. The adjectives table contains 4-byte entries:
  4294.  
  4295.     <dictionary address of word>  00  <adjective number>
  4296.     ----2 bytes-----------------  ----2 bytes----------- 
  4297.  
  4298. To make life more interesting, these entries are stored in reverse order
  4299. (i.e., lowest adjective number first).  The address of this table is
  4300. rather difficult to deduce from the file header information, so the constant
  4301. #adjectives_table is set up by Inform to refer to it.
  4302.  
  4303.  
  4304. GV2 is a much more suitable data structure, easier to read and write,
  4305. less limiting and marginally faster and more economical of Z-machine and
  4306. Inform memory.  In GV2 an individual grammar table has the format:
  4307.  
  4308.     <number of grammar lines>          1 byte
  4309.  
  4310. followed by that many grammar lines.  Individual lines are no longer always
  4311. 8 bytes long, as in GV1.  Instead they have the form:
  4312.  
  4313.     <action number>  <token 1> ... <token N>  <ENDIT>
  4314.     ----2 bytes----  -3 bytes-     -3 bytes-  -byte--
  4315.  
  4316. The action number is actually contained in the bottom 10 bits of the word
  4317. given first: the top five are reserved for future use, which leaves
  4318.  
  4319.     action_number & $400
  4320.  
  4321. as a bit meaning "reverse the order of the first and second parameters
  4322. if this action is to be chosen".
  4323.  
  4324. The ENDIT marker is the number 15.  There can be anything from 0 to 30
  4325. tokens, and each occupies three bytes, arranged as:
  4326.  
  4327.     <token type>   <token data>
  4328.     -- byte ----   --2 bytes---
  4329.  
  4330. Token type bytes are divided into the top two bits, the next two and the
  4331. bottom four.
  4332.  
  4333. The "next two bits" are used to indicate alternatives.  In a sequence of
  4334. tokens
  4335.  
  4336.     T1 / T2 / T3 / ... / Tn
  4337.  
  4338. then T1 will have $$10 in its "next two bits", and each of T2 to Tn will
  4339. have $$01.  Tokens not inside lists of alternatives always have $00.  (Note
  4340. that at present only prepositions are allowed as alternatives, but the
  4341. format is designed to open the possibility of extending this to all tokens.)
  4342.  
  4343. The bottom four are the "type" of the token.  The top two indicate what kind
  4344. of data is contained in the token data.  Strictly speaking this could be
  4345. deduced from the bottom six bits, but it's convenient for making backpatching
  4346. GV2 tables a simple matter within the compiler.
  4347.  
  4348.     Type  Means                       Data contains              Top bits
  4349.     0     illegal (never compiled)
  4350.     1     elementary token            0   "noun"                 00
  4351.                                       1   "held"
  4352.                                       2   "multi"
  4353.                                       3   "multiheld"
  4354.                                       4   "multiexcept"
  4355.                                       5   "multiinside"
  4356.                                       6   "creature"
  4357.                                       7   "special"
  4358.                                       8   "number"
  4359.                                       9   "topic"
  4360.     2     'preposition'               dictionary address         01
  4361.     3     noun = Routine              routine packed address     10
  4362.     4     attribute                   attribute number           00
  4363.     5     scope = Routine             routine packed address     10
  4364.     6     Routine                     routine packed address     10
  4365.  
  4366. GV2 makes no use of "adjective numbers" (so that dict_par3 is always zero
  4367. in GV2's dictionary words) and leaves both the adjectives table and the
  4368. preactions table empty.
  4369.  
  4370. There is one further difference between GV1 and GV2: in GV1, fake actions
  4371. are numbered from 256 upwards; in GV2, from 4096 upwards.
  4372.  
  4373.  
  4374. Note that although GV2 takes three bytes for a token as compared with GV1's
  4375. one byte, omission of the redundant null tokens and adjective table means
  4376. that when compiling a small "shell" library game, GV2 actually produces
  4377. more economical tables: 1920 bytes as opposed to 2337.
  4378.  
  4379. The first two entries in the following table are the real reason for GV2:
  4380.  
  4381.                                         Limit in GV1        Limit in GV2
  4382.  
  4383.     Prepositions per game               76                  unlimited
  4384.     Parsing routines (general ones,
  4385.        noun= filters, scope= routines
  4386.        all put together) per game       32                  unlimited
  4387.     Tokens per grammar line             6                   unlimited
  4388.     Actions per game                    256                 4096
  4389.     Inform verbs per game               256                 256
  4390.  
  4391. In practice the Inform compiler restrains the number of verbs (but that's
  4392. an adjustable memory setting) and lines per verb: in Inform 6.05 and earlier,
  4393. the maximum number of lines per verb is 20.  Inform 6.10 internally stores
  4394. grammar roughly as GV2 even when it's going to compile GV1 at the end, and
  4395. this allows a more economical use of Inform's memory: as a bonus, then, the
  4396. maximum number of lines per verb is raised to 32 in Inform 6.10.
  4397.  
  4398.  
  4399.     8.7   Value backpatching
  4400.           ------------------
  4401.  
  4402. Value backpatching is the final translation phase in Inform.  It is the
  4403. process of correcting temporary values which were written into the Z-machine
  4404. at a time when final values could not be known.
  4405.  
  4406. In addition to the Z-machine regions marked in the memory map above, the
  4407. symbols table also undergoes value backpatching: defined Constant symbols
  4408. flagged as CHANGE_SFLAG are backpatched as needed, before first use of their
  4409. values in backpatching something else.
  4410.  
  4411. The positions of such values have been "marked" with a "marker value"
  4412. indicating the type of value needed.  The backpatchable marker values are:
  4413.  
  4414.     Marker value       Significance of temporary value
  4415.  
  4416.     STRING_MV          Scaled address within static strings area
  4417.     ARRAY_MV           Byte address within dynamic array area
  4418.     IROUTINE_MV        Scaled address within Z-code area
  4419.     VROUTINE_MV        Veneer routine number (a *_VR value)
  4420.     NO_OBJS_MV         None
  4421.     INCON_MV           "Inform constant": the index in the #constants
  4422.                        keyword group (a *_SC value)
  4423.     DWORD_MV           Accession number of dictionary word
  4424.     INHERIT_MV         Byte address within common property values table
  4425.                        of the value which is being inherited here
  4426.     INHERIT_INDIV_MV   Ditto, but for individual property values table
  4427.     INDIVPT_MV         Offset in individual property values table
  4428.     MAIN_MV            None
  4429.     SYMBOL_MV          Index within symbols table
  4430.  
  4431. and these are backpatched as follows:
  4432.  
  4433.     Marker value       Final value
  4434.  
  4435.     STRING_MV          Packed address of static string
  4436.     ARRAY_MV           Byte address
  4437.     IROUTINE_MV        Packed address of routine
  4438.     VROUTINE_MV        Packed address of veneer routine
  4439.     NO_OBJS_MV         Number of objects in object tree
  4440.     INCON_MV           Value of constant (typically an address of some
  4441.                        Z-machine table)
  4442.     DWORD_MV           Byte address of word's entry in dictionary table
  4443.     INHERIT_MV         The value to inherit (after it has been backpatched)
  4444.     INHERIT_INDIV_MV   The value to inherit (after it has been backpatched)
  4445.     INDIVPT_MV         The byte address of this point in the individual
  4446.                        property valyes address
  4447.     MAIN_MV            Packed address of "Main" routine
  4448.     SYMBOL_MV          Value of symbol (after it has been backpatched)
  4449.  
  4450. The code NULL_MV is sometimes used to indicate "no marker", i.e., that a
  4451. value is correct as written.  Additional marker values also exist for
  4452. operands held within modules:
  4453.  
  4454.     IDENT_MV           Property identifier number
  4455.     ACTION_MV          Action number
  4456.     OBJECT_MV          Object number
  4457.     VARIABLE_MV        Variable number
  4458.  
  4459. (see chapter 10).  Note that modules are not value-backpatched at compilation
  4460. time, but at Link time.
  4461.  
  4462. Two different memory blocks are used to store backpatch markers: one for the
  4463. "Z-machine image", the byte-addressable memory at the bottom of the memory
  4464. map; and another for the Z-code area.  In the interests of economy, these use
  4465. different formats to hold marker data: see "bpatch.c".
  4466.  
  4467.  
  4468.     8.8   Packed address decoding
  4469.           -----------------------
  4470.  
  4471. Recall that the formula relating a packed address P to its byte address B is:
  4472.  
  4473.     B = 2P            version 3
  4474.         4P            versions 4 and 5
  4475.         4P + 8R       versions 6 and 7: routines
  4476.         4P + 8S       versions 6 and 7: static strings
  4477.         8P            version 8
  4478.  
  4479. In versions 6 and 7, R and S can be chosen fairly freely in the range 0 to
  4480. M/8, where M is the minimum address of a routine or static string as
  4481. appropriate.  The point is to expand the address space by making higher B
  4482. values available (whereas P has to lie within 0 and 65535): so one wants to
  4483. make R, S larger rather than smaller.  On the other hand, it's necessary to
  4484. the Inform language that the following are all different:
  4485.  
  4486.     (a) the number 0;
  4487.     (b) valid object numbers;
  4488.     (c) packed addresses of routines;
  4489.     (d) packed addresses of strings.
  4490.  
  4491. To be sure that (c) and (d) differ, Inform sets S = R.  To keep (c) from
  4492. (a) and (b), we must ensure that the packed address of every routine is at
  4493. least X, where X is slightly more than the largest object number.  Inform
  4494. also knows the byte address M of the lowest routine in memory ("Main__").
  4495. Note that
  4496.  
  4497.     M  =  4X + 8R
  4498.  
  4499. Inform therefore nudges up M and X to ensure that M and 4X are both divisible
  4500. by 8, and sets
  4501.  
  4502.     R  =  (M - 4X)/8
  4503.     S  =  R.
  4504.  
  4505. To compare this with the code: Write_Code_At is M; extend_offset is X;
  4506. scale_factor and length_scale_factor hold the magic constants 4 and 8.
  4507. code_offset and strings_offset are the scaled addresses of the first
  4508. routine and the first static string respectively, worked out by
  4509.  
  4510.     code_offset = 4X
  4511.     strings_offset = 4X + size of code area
  4512.  
  4513. The reason for having these is that when compilation was actually happening,
  4514. Inform did not know enough to calculate packed addresses, and instead
  4515. wrote scaled addresses starting from 0 for each area.  In backpatching,
  4516. then, Inform adds the above offsets to each packed address, and then they
  4517. come right.
  4518.  
  4519.  
  4520.     9   The run-time veneer
  4521.         -------------------
  4522.  
  4523.     9.1   Services provided by the veneer
  4524.           -------------------------------
  4525.  
  4526. The "veneer" is a thin section of code generated by Inform as an intermediate
  4527. layer between the code compiled from the source, and the Z-machine itself:
  4528. like the veneer on a table, it gilds the surface of the Z-machine, or so
  4529. the term is supposed to mean.
  4530.  
  4531. It consists of 27 routines, 4 class-objects, 2 properties and 2 global
  4532. variables, together with several arrays in the Z-machine's dynamic array
  4533. area.
  4534.  
  4535.  
  4536. The "veneer.c" section of Inform organises the compilation of the routines;
  4537. each one is compiled only if actually needed, and if no over-riding definition
  4538. has already been given in the source code.  (For instance, "PrintShortName"
  4539. is a veneer routine but the Inform library provides a much fuller version
  4540. than the one in "veneer.c".)
  4541.  
  4542. Note that the full Inform source code for these routines is present in
  4543. static strings in "veneer.c" (which are compiled using the lexer's "read
  4544. from a string" mode).
  4545.  
  4546. The routines come in four groups.  Note that names with double underscores
  4547. in are so chosen not to clash with identifiers used by the programmer.
  4548.  
  4549.    Main__        This is not really a routine at all, but is the piece of code
  4550.                  which the Z-machine's PC is initially set to.  It simply
  4551.                  makes a function call to Main(), and then quits.
  4552.  
  4553.    Box__Routine  Code to display an array of static strings in a black
  4554.                  "quotations" box, as required by the "box" statement.
  4555.  
  4556.    Printing routines   PrintShortName, DefArt, CDefArt, etc.
  4557.                  All normally over-ridden within the Inform library.
  4558.  
  4559.    Object orientation routines
  4560.                  Routines to implement message sending, access to individual
  4561.                  properties, "metaclass", "ofclass" and "provides".
  4562.  
  4563. Only the fourth group is interesting and the rest of this chapter is about
  4564. the veneer's implementation of the "object orientation" features new in
  4565. Inform 6 and which for the first time provide a major data structure not
  4566. present in the Z-machine architecture.
  4567.  
  4568. Since veneer routines are compiled at the end of the pass (when it's known
  4569. which will be needed), the code area looks like this:
  4570.  
  4571.      start of code area -->      00             (routine header for Main__)
  4572.        initial PC value -->      @call_1n Main
  4573.                                  @quit
  4574.  
  4575.                                  ... routines as defined in source code...
  4576.                                  
  4577.                                  veneer routines as required, in order
  4578.                                  of appearance in the "veneer.c" table
  4579.  
  4580. (Note that Main__ is assembled as a routine.  In the Version 6 Z-machine, this
  4581. is called to begin execution.  In other versions, the initial PC value is
  4582. set to the call_1n instruction -- which is why Main__ must be first: the
  4583. initial PC value has to lie in the bottom 64K of Z-machine memory.
  4584. Note also: for the Versions 3 and 4 Z-machine more primitive call opcodes are
  4585. used to get into Main.)
  4586.  
  4587.  
  4588. The four objects in the veneer are the class-objects for the four metaclasses
  4589. defined in all Inform programs: Class, Object, Routine and String.  The
  4590. object tree therefore looks like this:
  4591.  
  4592.     1     Class
  4593.     2     Object
  4594.     3     Routine
  4595.     4     String
  4596.           ... objects and class-objects as defined in source code ...
  4597.  
  4598. The two global variables are "self" and "sender", used in message-passing,
  4599. and which are two of the 7 highest-numbered global variables which Inform
  4600. reserves to its own use as "registers".
  4601.  
  4602.  
  4603.     9.2   Properties 2 and 3, "ofclass" and "metaclass"
  4604.           ---------------------------------------------
  4605.  
  4606. Inform reserves common properties 2 and 3 to itself, and uses them as follows:
  4607.  
  4608.     property 2 (additive): a word array containing the class-object numbers
  4609.         of all classes of which this object is a member; the property is
  4610.         absent if the object belongs to no classes.  (Note that metaclasses
  4611.         do not appear here: all non-class-objects are members of Object,
  4612.         but Object is not listed here.)
  4613.  
  4614.     property 3: a byte address pointing to the individual properties table
  4615.         for this object; property 3 is absent if it has no individual
  4616.         properties.
  4617.  
  4618. The veneer tests "X ofclass Y" according to the rules:
  4619.  
  4620.     if X is a valid Z-machine object number:
  4621.         if X is a class-object (tested by: if X is a child of Class)
  4622.             then only if Y is Class
  4623.         otherwise only if Y appears in the property 2 list for X
  4624.  
  4625.     if X is the packed address of a routine: only if Y is Routine
  4626.  
  4627.     if X is the packed address of a string:  only if Y is String
  4628.  
  4629. giving a run-time error if Y isn't a class-object.  Note that determining
  4630. which of these ranges contains X needs code essentially the same as that
  4631. in the Inform 5/12 library routine "ZRegion": indeed, this is how the
  4632. veneer routine implementing the "metaclass" function works.
  4633.  
  4634.  
  4635.     9.3   Class numbering and class objects
  4636.           ---------------------------------
  4637.  
  4638. In Inform 6 each class definition results in the creation of a related
  4639. object, the class-object for that class.
  4640.  
  4641. Class objects have:
  4642.  
  4643.     their internal symbol-name as short name;
  4644.     no attributes (*);
  4645.     no (common) properties except possibly for property 3.
  4646.  
  4647. All except for Class are placed in the object tree as children of Class.
  4648.  
  4649. Immediately following the property values table for a class (which is bound
  4650. to be short, since it can only contain the short name and perhaps property 3)
  4651. is a six-byte block of attributes which would be inherited from the class (*),
  4652. and then a second property values table, specifying the properties which
  4653. members of the class would inherit from it.  (These values are accessed at
  4654. run time to implement the superclass access operator :: when applied to a
  4655. common property.)
  4656.  
  4657. Property 3 is used to hold the byte address of the individual properties 
  4658. table of properties which members would inherit.  It is absent if there
  4659. are no such properties.  (These are accessed at run-time to implement the
  4660. superclass access operator :: when applied to an individual property.)
  4661.  
  4662. Note that there are two numbering systems used for classes: the "class
  4663. number" counts 0, 1, 2, 3, ... in order of declaration, with Class numbered
  4664. 0.  (This is used in superclass message number coding.)  Classes are also
  4665. referred to by the object numbers of their class objects.  It's necessary
  4666. to be able to convert between the two at run time; the "class numbers table"
  4667. is a word array whose Nth entry is the class-object number corresponding to
  4668. class number N.
  4669.  
  4670. [(*) This is a change made in Inform 6.12.  Previously, class objects
  4671. had the attributes which would be inherited from the class.  6.12 moves
  4672. this information to a harmless block of six bytes elsewhere, essentially
  4673. so that loops like "objectloop (x has animate)" would not pick up classes
  4674. as well as objects.]
  4675.  
  4676.  
  4677.     9.4   Individual property identifiers
  4678.           -------------------------------
  4679.  
  4680. Just as the common properties are identified by property numbers 1 to 63,
  4681. so the individual properties are identified by numbers 64 upward.  The
  4682. group 64 to 71 is used to identify the properties provided by inheritance
  4683. from the metaclasses:
  4684.  
  4685.     Id    Name                Provided by
  4686.  
  4687.     64    create              class-objects other than metaclass-objects
  4688.     65    recreate            ditto
  4689.     66    destroy             ditto
  4690.     67    remaining           ditto
  4691.     68    copy                ditto
  4692.     69    call                objects of metaclass Routine
  4693.     70    print               objects of metaclass String
  4694.     71    print_to_array      ditto
  4695.  
  4696. However, in addition to this a property ID number with its top bit set has
  4697. a special meaning:
  4698.  
  4699.     Bit    16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1
  4700.            set --------------------------   -----------------------------
  4701.                      entry number                    class number
  4702.                within class's i.p. table
  4703.                    (counting from 0)
  4704.  
  4705. which means "the given class's inheritable value of the property with this
  4706. ID number", and is used to implement the "superclass" operator as something
  4707. which acts on ID numbers:
  4708.  
  4709.           Class :: identifier
  4710.  
  4711. is implemented by writing the class number into the bottom bits and searching
  4712. as above.  Further, a property ID number in the form:
  4713.  
  4714.     Bit    16  15  14  13  12  11  10   9   8   7   6   5   4   3   2   1
  4715.            00  set  ---------------------   -----------------------------
  4716.                     common prop number              class number
  4717.  
  4718. refers to "the given class's inheritable value of this common property".
  4719.  
  4720. As a special rule, in the case of class Object this accesses the Z-machine
  4721. default property value.  Thus, since the library defines
  4722.  
  4723.     Property cant_go "You can't go that way.";
  4724.  
  4725. then X.Object::cant_go will always evaluate to "You can't go that way."
  4726. for any Object X.
  4727.  
  4728.  
  4729. Note that the need to be able to pack such descriptions into 16 bits is one
  4730. reason classes need to have a 0, 1, 2, ... numbering system in addition
  4731. to the class-object system of numbering (which has many lacunae).  Even as
  4732. it is, the present veneer implementation constrains us to a maximum of 256
  4733. class definitions, each able to provide at most 128 individual properties
  4734. (in addition to the potentially 63 declared as common using Property);
  4735. more work may be needed to alleviate this at a later date.
  4736.  
  4737.  
  4738.     9.5   Individual property tables
  4739.           --------------------------
  4740.  
  4741. For each object that provides any individual properties at all, property
  4742. 3 holds the byte address of its individual property table.  The entries
  4743. in this table are pairs of identifier number and current value: thus,
  4744.  
  4745.    raw identifier number (2 bytes)
  4746.        but with top bit set if "private" to the object in question
  4747.    property length (1 byte)
  4748.    current value (as many bytes as specified in the property length,
  4749.        though this will always be an even number >= 2)
  4750.  
  4751. terminated by a zero word, 00 00.  (Note that there is no property 0,
  4752. common or individual.)
  4753.  
  4754. The properties can occur in any order and need not be in numerical order
  4755. of their IDs (which is helpful to assist linking, though it may have speed
  4756. implications).  The following Inform code prints out an object's table:
  4757.  
  4758.     [ IndivTable obj x n;
  4759.       x = obj.3;
  4760.       if (x == 0) rfalse;
  4761.       print "Table for ", (object) obj, " is at ", (hex) x, "^";
  4762.       while (x-->0 ~= 0)
  4763.       {   print (hex) x-->0, " (", (property) x-->0, ")  length ", x->2, ": ";
  4764.           for (n = 0: n< (x->2)/2: n++)
  4765.               print (hex) (x+3)-->n, " ";
  4766.           new_line;
  4767.           x = x + x->2 + 3;
  4768.       }
  4769.     ];
  4770.  
  4771.     [ hex x y;
  4772.       y = (x & $ff00) / $100;
  4773.       x = x & $ff;
  4774.       print (hdigit) y/$10, (hdigit) y, (hdigit) x/$10, (hdigit) x;
  4775.     ];
  4776.  
  4777.     [ hdigit x;
  4778.       x = x % $10;
  4779.       if (x<10) print x; else print (char) 'a'+x-10;
  4780.     ];
  4781.  
  4782.  
  4783. From an inheritance point of view, individual properties are always
  4784. non-additive: a specified value overrides and replaces an inherited value.
  4785. (The idea is that access to superclass values is a more elegant alternative
  4786. to using additive properties to make class values remain available to
  4787. inheritors which have altered them.)
  4788.  
  4789.  
  4790. The veneer contains routines to implement "provides", ".", ".&" and ".#",
  4791. together with routines to apply ++ and -- as pre- or postfix operators,
  4792. and a routine to implement = in the context of individual properties.
  4793. These all lapse back into ordinary Z-machine instructions for common
  4794. properties if they find a property number in the range 1 to 63.
  4795.  
  4796. Note that the veneer's implementation of "provides" contains a special
  4797. rule meaning that class-objects do not provide any properties except the
  4798. five inherited from the metaclass Object, even though they have a table
  4799. in the above format (which contains the inheritable values).
  4800.  
  4801.  
  4802. The veneer's highest-level routine sends a message to an individual
  4803. property.  (This same routine contains implementations of the eight messages
  4804. numbered 64 to 71.)  Note that the trickiest part is keeping "self" and
  4805. "sender" right:
  4806.  
  4807.     push the current "self" value
  4808.     push the current "sender" value
  4809.     set "sender" to "self"
  4810.     set "self" to the destination object
  4811.     now make the function call
  4812.     pull to "sender"
  4813.     pull to "self"
  4814.  
  4815.  
  4816. Note that the object creation/deletion system works in a quite simple way:
  4817. the pool of uncreated duplicate members of a class are exactly the children
  4818. of its class-object.  Objects are re-initialised when they are returned to
  4819. this pool, leaving them "fresh" and ready for recreation.
  4820.  
  4821.  
  4822.     9.6   Availability of symbol names at run-time
  4823.           ----------------------------------------
  4824.  
  4825. It is not possible to determine at compile-time if a message is wrongly
  4826. addressed, i.e., if a message is sent to property X of object O but object O
  4827. does not provide X.  For one thing, availability depends on who is calling
  4828. (if the property is private to O); for another, message identifiers do not
  4829. need to be constants.
  4830.  
  4831. Therefore a good error-reporting mechanism is needed at run-time; errors like
  4832. "Object 32 has no property 57" would make debugging hopelessly difficult.
  4833. The only way to achieve this is for the property names to be available at
  4834. run time.  Similarly, it's helpful for debugging purposes if attribute
  4835. names and action names can also be available.
  4836.  
  4837.  
  4838. To this end, Inform compiles a table of identifier names into every
  4839. story file (though not into modules) and provides a system constant called
  4840. #identifiers_table pointing to the start of the table.  The table contains:
  4841.  
  4842.     --> 0      = Number of property names plus 1 = P
  4843.     --> 1      = Packed address of string containing name of property 1
  4844.     to
  4845.     --> (P-1)  = Packed address of string containing name of property P-1
  4846.                  (properties 1 to 63 will be common, and subsequent ones
  4847.                  individual: this table includes both kinds; note that
  4848.                  there is no property numbered 0)
  4849.  
  4850.     --> P      = Packed address of string containing name of attribute 0
  4851.     to
  4852.     --> (P+47) = Packed address of string containing name of attribute 47
  4853.  
  4854.     --> (P+48) = Packed address of string containing name of action 0
  4855.     and so on.
  4856.  
  4857. In the case of (common) property and attribute names, the ability of
  4858. programmers to "alias" names together means that these names will sometimes
  4859. be given as a list of possibilities with slashes in between.
  4860.  
  4861. Note that printing property names so as to properly handle usage of ::
  4862. is harder than simply looking up in this table (for instance, there are
  4863. times when the right output should look like "Coin::value").  Inform
  4864. provides the construct
  4865.  
  4866.     print (property) X;
  4867.  
  4868. to handle this.  But the corresponding cases for attributes and actions
  4869. are easier.  Simply define:
  4870.  
  4871.     [ DebugAction a anames;
  4872.       if (a>=256) print "<fake action ", a-256, ">";
  4873.       anames = #identifiers_table;
  4874.       anames = anames + 2*(anames-->0) + 2*48;
  4875.       print (string) anames-->a;
  4876.     ];
  4877.     [ DebugAttribute a anames;
  4878.       if (a<0 || a>=48) print "<invalid attribute ", a, ">";
  4879.       else
  4880.       {   anames = #identifiers_table; anames = anames + 2*(anames-->0);
  4881.           print (string) anames-->a;
  4882.       }
  4883.     ];
  4884.  
  4885. (These are in fact both part of Library 6/3 anyway: a different DebugAction
  4886. routine is present in Library 6/1 and 6/2 if DEBUG is set.)  You can then:
  4887.  
  4888.     print (DebugAction) X;
  4889.     print (DebugAttribute) X;
  4890.  
  4891.  
  4892. It is also for error reporting that the names of the classes are needed at
  4893. run-time, which is why the short name of a class-object is the name of the
  4894. class.
  4895.  
  4896.  
  4897.    10   Compiling and linking modules
  4898.         -----------------------------
  4899.  
  4900.    10.1   Model
  4901.           -----
  4902.  
  4903. The model for linking is that a game being compiled (called the "external"
  4904. program) may Link one or more pre-compiled sections of code called "modules". 
  4905. Suppose the game Jekyll has a subsection called Hyde.  Then these two
  4906. methods of making Jekyll are (almost) equivalent:
  4907.  
  4908. (i)  Putting Include "Hyde"; in the source code for "Jekyll", and
  4909.      compiling "Jekyll".
  4910.  
  4911. (ii) Compiling "Hyde" with the -M ("module") switch set, putting
  4912.      Link "Hyde"; into the same point in the source code for "Jekyll",
  4913.      and compiling "Jekyll".
  4914.  
  4915. Option (ii) is of course much faster if "Hyde" does not change very often,
  4916. since its ready-compiled module can be left lying around while "Jekyll"
  4917. is being developed.
  4918.  
  4919. Option (ii) also slightly increases story file size, as some code
  4920. optimisations are impossible this way: e.g., linking rather than including
  4921. the library costs about 160 bytes on final story file size.
  4922.  
  4923.  
  4924. In the linking process, two incarnations of Inform need to communicate with
  4925. each other:
  4926.  
  4927.     A.  one in the middle of compiling a story file
  4928.         and wanting to link a module into it;
  4929.  
  4930.     B.  one compiling a module for future linking into
  4931.         some unknowable story file.
  4932.  
  4933. To be more precise, B needs to send information to A.  It does so by writing
  4934. a modified form of story file with additional tables attached, and this is
  4935. what a module is.
  4936.  
  4937. We discuss how Inform copes with situation A first, as this indicates the
  4938. information which B needs to send it; we then discuss how B gathers and
  4939. sends this information.
  4940.  
  4941. Note that A and B can never apply in the same run-through of Inform, since
  4942. a module cannot link another module into it.
  4943.  
  4944. Finally, note that A and B may be different ports of Inform running on
  4945. different machines at different times, since the module format is
  4946. machine-independent.
  4947.  
  4948.  
  4949.    10.2   Linking a module
  4950.           ----------------
  4951.  
  4952. There are two tasks: (a) merging the module's data structures into those of
  4953. the external story file, and (b) mending all the constants used in these data
  4954. structures which couldn't be known at module compilation time.
  4955.  
  4956. (a) Merging data structures
  4957.  
  4958. This is formidably hard, since it means extracting tables in Z-machine format
  4959. and putting them back into Inform's own (usually higher-level) data
  4960. structures: in effect, an inverse is needed for each translation operation.
  4961. The following table briefly lists the data structures which are merged, and
  4962. how this is done:
  4963.  
  4964.    Structure                        Method
  4965.  
  4966.    Initial global variable values   Directly copy in
  4967.    Initial array entry states       Append
  4968.    Code area                        Append.  Z-code is relocatable except
  4969.                                       that function calls are to absolute
  4970.                                       addresses: these are handled as though
  4971.                                       they were references to constants
  4972.                                       unknown at module compilation time
  4973.    Static strings area              Append
  4974.    Dictionary                       Extract words from the module, one at
  4975.                                       a time, and insert into the story
  4976.                                       file's dictionary.  (The dictionary
  4977.                                       is just too complex to merge the
  4978.                                       internal structures.)
  4979.    Object tree                      Append, and also fix all the object
  4980.                                       numbers used in parent, sibling and
  4981.                                       child fields: a particular concern
  4982.                                       is with classes defined in the
  4983.                                       module, which have to be added as
  4984.                                       children of the main program's
  4985.                                       Class object
  4986.    Property values area             Append
  4987.    Individual property values       Append
  4988.    "Flags 2" header bits            Bitwise OR
  4989.    Class to object numbers table    Effectively append, moving the object
  4990.                                       numbers up appropriately.  The
  4991.                                       module's class numbers table contains
  4992.                                       offsets of the class inheritance
  4993.                                       property blocks as well, and these
  4994.                                       are appended too
  4995.  
  4996. (b) Mending references
  4997.  
  4998. The problem here is to absorb numerous references within the module into
  4999. the backpatch table for the story file.  It is not possible just to append
  5000. the module's backpatch tables onto the story file's backpatch tables:
  5001. all the offsets need adjusting, and certain kinds of backpatching need to
  5002. take place immediately (to fix the four marker values not allowable in
  5003. story file backpatch tables, ACTION_MV, IDENT_MV, VARIABLE_MV and OBJECT_MV).
  5004.  
  5005.  
  5006.    10.3   Imports and exports
  5007.           -------------------
  5008.  
  5009. The main "extra" ingredients in a module (compared with an ordinary story
  5010. file) are: two backpatching tables (see the next section), and an
  5011. import/export table giving the names of symbols to be shared with the main
  5012. story file which will link in with it.
  5013.  
  5014. The language of "imports and exports" considers the module to be the home
  5015. country, and the external program to be foreign.  (An exported symbol's value
  5016. is assigned in the module and used in the external program; an imported
  5017. symbol's value is assigned in the external program and used in the module.)
  5018.  
  5019. An export is a symbol defined in the module which may be referred to
  5020. in the external program.  All variables, routines and general constants
  5021. defined in the module except for (a) system-defined symbols always present
  5022. (such as "Class", "true", etc.) and (b) attributes, common properties and
  5023. labels are exported.
  5024.  
  5025. An import is a symbol name used in compiling the module which isn't defined
  5026. within it.  During module compilation, just as in story file compilation, if
  5027. an unknown name is hit then an operand is constructed which is marked
  5028. SYMBOL_MV and has the symbol index as its value.  In the case of a story
  5029. file, at value backpatching time the correct value is found out and written
  5030. in.  In the case of a module, there is no value backpatching phase.
  5031.  
  5032. Instead, all symbols are flagged with IMPORT_SFLAG if ever used when undefined
  5033. (i.e., if any SYMBOL_MV marker is ever issued).  Any which remain undefined
  5034. at the end of module compilation (in fact, at the same point where exports
  5035. are made) are "imported": that is, their names are written down so that their
  5036. existence can be checked on at Link time.  It is an error for any imported
  5037. symbol not to exist in the external program performing the Link.
  5038.  
  5039. Note, therefore, that backpatch markers in the module with marker value
  5040. SYMBOL_MV may refer either to symbols which were assigned values later on
  5041. during module compilation (and are thus exported) or to symbols which were
  5042. never assigned values (and are thus imported).
  5043.  
  5044.  
  5045.    10.4   Backpatch backpatching
  5046.           ----------------------
  5047.  
  5048. Although modules undergo branch backpatching and optimisation just as story
  5049. files do, they do not undergo value backpatching.
  5050.  
  5051. Instead, the two value-backpatching tables (zcode_backpatch_table and
  5052. zmachine_backpatch_table) are appended to the module file.  The basic idea
  5053. is that when the external file merges the module's data structures into its
  5054. own, it also adds the module's backpatch markers into its own collection. 
  5055. Thus, the module's code and data are finally value-backpatched when the
  5056. external program is value backpatched.
  5057.  
  5058. Unfortunately, these backpatch markers have addresses which are correct for
  5059. the module, but wrong for the external program: they require correction
  5060. before they can be transferred, and this is called "backpatch backpatching".
  5061.  
  5062. In addition to this, a few special types of backpatch markers (only ever
  5063. generated inside modules, never in story files) are dealt with immediately.
  5064.  
  5065. A further complication is that the module may have exported a symbol which
  5066. itself has a value needing backpatching.  For example, if the module contains
  5067.  
  5068.     Constant Swine 'hog';
  5069.  
  5070. then, in its symbol table, the symbol Swine will have the marker DWORD_MV
  5071. attached to its value.  When this is exported to the external program, the
  5072. symbol value will need backpatch-backpatching.
  5073.  
  5074.  
  5075. The sequence of events is roughly:
  5076.  
  5077.      1.  Load the module into an allocated block of memory.
  5078.      2.  Merge the dictionary, finding out which dictionary
  5079.          accession numbers in the external program correspond to
  5080.          which in the module.
  5081.      3.  Go through the import/export table, until we know
  5082.          which symbol numbers in the module correspond to which
  5083.          symbol numbers in the external program; and which
  5084.          variable numbers to which; and which action numbers
  5085.          to which; and which property identifiers to which.
  5086.          (Arrays called "maps" are created to encode all these.)
  5087.      4.  Backpatch, or deal with the backpatch markers attached to,
  5088.              any exported symbols from the module.
  5089.      5.  Go through the Z-code backpatch table:
  5090.              deal with IDENT_MV, ACTION_MV, VARIABLE_MV and OBJECT_MV markers
  5091.                  immediately, by backpatching the copy of the module
  5092.                  held in memory;
  5093.              backpatch the other markers and then transfer them
  5094.                  into the external program's Z-code backpatch table.
  5095.      6.  Do the same for the Z-machine backpatch table.
  5096.      7.  Now merge the memory copy of the module into the external
  5097.          program.
  5098.  
  5099. (There are actually 17 stages, but most of the latter ones are mergers of
  5100. different tables which can happen in any order.)
  5101.  
  5102. As an example of "backpatch backpatching", the backpatch marker for the
  5103. quantity 'hog' will be DWORD_MV, with value the accession number of the word
  5104. "hog" in the module's dictionary.  This accession number needs to be changed
  5105. to the accession number of "hog" in the story file's dictionary.
  5106.  
  5107. The four "module only" backpatch marker values are:
  5108.  
  5109.     VARIABLE_MV             global variable number in module's set
  5110.     OBJECT_MV               object number in the module's tree
  5111.     IDENT_MV                identifier number in the module's set
  5112.     ACTION_MV               action number (always between 0 and 255, though
  5113.                               always in a "long" constant so that a fake
  5114.                               action number can be backpatched over it)
  5115.  
  5116. Note that within the module, there is no way to tell an externally defined
  5117. action from a fake action.  That is, the reference ##Duckling might be
  5118. to an external action or fake action called "Duckling".  Within the module,
  5119. it is created as an action name in the usual way; at Link time, the action
  5120. map corresponds this module action number to a fake action number or a real
  5121. one as required.
  5122.  
  5123. Variable numbers in the module are not marked if they are local (or the
  5124. stack pointer), or if they are from the system set ("self", "sender" and so
  5125. on), whose numbers are guaranteed to be correct already.  In a module, the
  5126. available variable numbers are 16 to N-1, where N is the number of the lowest
  5127. system-used variable (at present, 249).  Imported variables are numbered
  5128. from 16 upwards, and variables defined newly in the module from N-1
  5129. downwards.  If these allocations collide in the middle, then the Z-machine
  5130. has run out of variables.
  5131.  
  5132.  
  5133.    10.5   How modules differ from story files
  5134.           -----------------------------------
  5135.  
  5136. Module files are identical to story files, except that they have not
  5137. undergone value backpatching, and do not contain any part of the veneer; and
  5138. except as detailed below.
  5139.  
  5140. (i)  Size
  5141. ---------
  5142. A module is at most 64K in size.
  5143.  
  5144. (ii) Header entries (where different from story file header entries)
  5145. --------------------------------------------------------------------
  5146.     Byte   Contents
  5147.  
  5148.     0      64 + V  (where V is the version number)
  5149.     1      module version number
  5150.     6,7    byte address of the module map table
  5151.            (note that this is the "initial PC value" slot in the
  5152.            story file header format, but no such value is meaningful
  5153.            for modules)
  5154.  
  5155. V is used to make sure that we aren't trying to link, e.g., a Version 5
  5156. module into a Version 8 story file: this would cause heaps of backpatch
  5157. errors, as the packed addresses would all be wrong.  Although we could
  5158. in principle automatically fix them all up, it isn't worth the trouble:
  5159. the user only needs to compile off suitable versions of the modules.
  5160.  
  5161. The module version number is a version number for the module format
  5162. being used: this document describes module version 1.
  5163.     
  5164. (iii) Class numbers table
  5165. -------------------------
  5166. In a module, the class numbers table contains additional information,
  5167. and has the form:
  5168.  
  5169.     <word containing object number for Class>
  5170.     <word containing class 1 inheritance-properties block offset>
  5171.     <word containing object number for class 1>
  5172.     <word containing class 1 inheritance-properties block offset>
  5173.     <word containing object number for class 2>
  5174.     <word containing class 2 inheritance-properties block offset>
  5175.     ...
  5176.     <word containing object number for class N>
  5177.     <word containing class N inheritance-properties block offset>
  5178.     00 00
  5179.   
  5180. (In a story file, the inheritance-properties block offsets are absent.)
  5181.  
  5182. (iv) Identifier names table
  5183. ---------------------------
  5184. This is missing altogether in a module.
  5185.  
  5186. (v) Dictionary
  5187. --------------
  5188. A module dictionary is in accession order, not alphabetical order.  (This is
  5189. necessary so that backpatch markers in the module, which refer to dictionary
  5190. words by accession number, can be connected with their original words at
  5191. link time.)
  5192.  
  5193. (vi) Module map
  5194. ---------------
  5195. The module map is (currently) 15 words long and contains the following:
  5196.  
  5197.     Word 0   byte address of object tree
  5198.          1   byte address of common property values table
  5199.          2   scaled address of static strings table
  5200.          3   byte address of class numbers table
  5201.          4   byte address of individual property values table
  5202.          5   number of bytes in indiv prop values table
  5203.          6   number of symbols in module's symbols table
  5204.          7   number of property identifier numbers used in module
  5205.          8   number of objects present in module
  5206.          9   byte address of import/export table
  5207.         10   its size in bytes
  5208.         11   byte address of Z-code backpatch table
  5209.         12   its size in bytes
  5210.         13   byte address of Z-machine image backpatch table
  5211.         14   its size in bytes
  5212.  
  5213. The map serves as an extension to the header, which has more or less run out
  5214. of available slots for new pieces of information.
  5215.  
  5216. (vii) Parents of class objects
  5217. ------------------------------
  5218. Objects representing classes are given in the object tree as having
  5219. parent $7fff (and having next-object 0, as if each were an only child).
  5220. These are to be understood as being children of the Class object (which
  5221. is not present in a module).
  5222.  
  5223. (viii) Import/export table
  5224. --------------------------
  5225. This is a sequence of symbols (mixing up imports and exports in no particular
  5226. order), occupying records as follows:
  5227.  
  5228.     Record type (1 byte)
  5229.     Symbol number in module symbols table (2 bytes)
  5230.     Symbol type (1 byte)
  5231.     Symbol backpatch marker (1 byte)
  5232.     Symbol value (2 bytes)
  5233.     Symbol name (null terminated)
  5234.  
  5235. where the possible record types are:
  5236.  
  5237.     IMPORT_MV                   import a symbol
  5238.                                 (in which case the symbol backpatch marker
  5239.                                 is omitted)
  5240.  
  5241.     EXPORT_MV                   export a symbol defined in a non-system file
  5242.     EXPORTSF_MV                 export a symbol defined in a system file
  5243.     EXPORTAC_MV                 export an action name (in the form
  5244.                                     "Name__A")
  5245.  
  5246. Note: we need to distinguish between EXPORT_MV and EXPORTSF_MV in order to
  5247. make Replacement of routines work properly.  Suppose the user asks to Replace
  5248. the routine DrawStatusLine, normally found in the parser, and then links the
  5249. parser module and also a module of his own containing his new definition of
  5250. DrawStatusLine.  The linker knows which of these to accept because the first
  5251. was compiled from a system module, and thus exported with EXPORTSF_MV, while
  5252. the second was not, and was exported with EXPORT_MV. Other than for this
  5253. purpose, the two values are treated equivalently.
  5254.  
  5255. (ix) Z-code backpatch table
  5256. ---------------------------
  5257. This is exactly the module's Z-code backpatch table, no different in format
  5258. from that used for backpatching story files (except that four additional
  5259. marker values are permitted).
  5260.  
  5261. (x) Z-machine image backpatch table
  5262. -----------------------------------
  5263. This is exactly the module's Z-machine backpatch table, no different in
  5264. format from that used for backpatching story files (except that four
  5265. additional marker values are permitted).
  5266.  
  5267.  
  5268.    10.6   Restrictions on what modules may contain
  5269.           ----------------------------------------
  5270.  
  5271. [1] It is impractical to allow the module and the external program use of
  5272.     each others' attribute and property names, because there is no rapid way
  5273.     of repairing the module's object tables.  Instead, both program and
  5274.     module must use the same Include file to make the same attribute and
  5275.     property definitions as each other.
  5276.  
  5277. [2] An object defined in a module cannot:
  5278.     (a) have an externally-defined parent object,
  5279.     or (b) inherit from an externally-defined class.
  5280.  
  5281. [3] A module can only use externally-defined global variables if they have
  5282.     been explicitly "imported" using the Import directive.
  5283.  
  5284. [4] A module cannot use Verb or Extend: that is, it cannot define grammar.
  5285.  
  5286. [5] A module cannot use Stub or Default (for obvious reasons).
  5287.  
  5288. [6] A module cannot use "unknown at compile time" constants in every
  5289.     context.  (Unknown in that, e.g., 'frog' and MAX_FROGS might be
  5290.     unknown: the former because the dictionary address of 'frog' in the
  5291.     final program can't be known yet, the latter (say) because MAX_FROGS
  5292.     is a constant defined only in the external program.)  In the
  5293.     following list of contexts in which constants occur in Inform source
  5294.     code, those marked with a (*) are not permitted to be "unknown at
  5295.     compile time":
  5296.  
  5297.         1. In high-level source code (including as a switch value and
  5298.            a static string in a "box" or "string" statement).
  5299.         2. In assembly language source code.
  5300.         3. As the initial entries in an array.
  5301.         4. As the initial value of a variable.
  5302.         5. In a CONSTANT definition.
  5303.         6. As an object's (common or individual) property value.
  5304.     *   7. As a release number.  (Defining the module release number only.)
  5305.     *   8. As a version number.  (Modules are always version 5.)
  5306.     *   9. In grammar.  (You can't define grammar in a module.)
  5307.     *  10. As the size of an array.
  5308.     *  11. In a DEFAULT constant definition.  (You can't use Default.)
  5309.     *  12. In an IFTRUE or IFFALSE condition.
  5310.     *  13. As a property default value (though this is unnecessary since
  5311.            the definitions in the outside program take precedence).
  5312.     *  14. As the number of duplicate objects provided for a class.
  5313.  
  5314.     Only (10) and (14) are restrictive.  Combining a module with a short
  5315.     Include file to make such definitions will get around them.
  5316.  
  5317.  
  5318.    11   Service levels
  5319.         --------------
  5320.  
  5321.    11.1   Variables and arrays
  5322.           --------------------
  5323.  
  5324. Each of the sections is responsible for the initialisation of its own
  5325. variables, and for the allocation and deallocation of its own arrays.  To
  5326. this end, every section except "inform.c" (which is considered to be in
  5327. charge of the others) provides a set of four routines to manage its
  5328. data structures:
  5329.  
  5330.     init_*_vars()           called when the compiler is beginning a run
  5331.     *_begin_pass()          called at the beginning of the compilation
  5332.                             pass through the source code: this usually sets
  5333.                             some of the variables
  5334.     *_allocate_arrays()     called when the compiler is beginning a run
  5335.     *_free_arrays()         called when the compiler is ending its run
  5336.  
  5337. Note that *_free_arrays() must exactly undo what *_allocate_arrays() has
  5338. done.
  5339.  
  5340. The 19 routines of each kind are polled in no particular order (actually,
  5341. in alphabetical order).
  5342.  
  5343. Note that there are also
  5344.  
  5345.     lexer_begin_prepass()
  5346.     files_begin_prepass()
  5347.  
  5348. which need to happen even earlier than the general *_begin_pass() poll,
  5349. and also
  5350.  
  5351.     lexer_endpass()
  5352.     linker_endpass()
  5353.  
  5354. but since the other sections generally don't need to do anything at end
  5355. of pass, it wasn't worth making a formal poll of it.
  5356.  
  5357. Static initialisation of variables is only allowed when they are certain
  5358. never to change (for example, the string containing the accent escape
  5359. characters never changes).
  5360.  
  5361.  
  5362.    11.2   Memory allocation and deallocation
  5363.           ----------------------------------
  5364.  
  5365. All allocation and deallocation is routed through routines given in
  5366. "memory.c": specifically,
  5367.  
  5368.     my_malloc()   and   my_free()
  5369.  
  5370. Note that these are called with a string as an extra parameter (as compared
  5371. with malloc() and free()), which is used to print helpful error messages in
  5372. case of collapse.  This is where the -m ("print the memory allocation") switch
  5373. is implemented, and it's also a good place to add any OS-specific code which
  5374. may be needed.
  5375.  
  5376. This may be needed because, under ANSI rules, malloc() is entitled to refuse
  5377. to allocate blocks of memory any larger than 32K minus a few bytes.  On a few
  5378. implementations malloc() actually does this, even on very large machines,
  5379. because it's convenient to avoid memory segmentation problems.  (For instance,
  5380. on a few versions of C for the Macintosh, it's possible to have 16M free
  5381. and still be refused a request for 33K of it.)  Consequently it may be
  5382. necessary to use some compiler-specific routine instead.
  5383.  
  5384. Inform allocates many arrays (50 or so) and in a normal compilation run,
  5385. the largest of these occupies about 26K.  However, the implementation of
  5386. Link requires the whole of a module file to be held in one contiguous block
  5387. of memory, potentially 64K long; and the same applies to the array holding
  5388. the unpaged memory area of the Z-machine during construct_storyfile().
  5389.  
  5390. Failure of my_malloc() causes a fatal error.
  5391.  
  5392.  
  5393. Inform also provides a structure (memory_block) for allocating extensible
  5394. regions of memory (at a slight access-speed penalty): these allocate
  5395. 8K chunks as needed.  Three of these are used as alternatives to the
  5396. temporary files when -F0 is operating, and two more are used to hold
  5397. backpatch markers.
  5398.  
  5399.  
  5400.    11.3   Error messages
  5401.           --------------
  5402.  
  5403. All diagnostic and error messages are routed through the "errors.c" section
  5404. (except for errors in parsing ICL, as this takes place before the compiler
  5405. itself is active).
  5406.  
  5407. There are three kinds of diagnostic: warning, error and fatal error.
  5408. Fatal errors cause Inform to halt with an exit(1), which is about as fatal
  5409. as anything can be to a C program.  (Fatal errors are mainly issued when the
  5410. memory or file-handling environment seems to have gone wrong.)  Errors
  5411. allow compilation to carry on, but suppress the production of any output
  5412. at the end: in some ways this is a pity, but there are not many errors which
  5413. one can be confident of safely recovering from.
  5414.  
  5415. Note that a sequence of MAX_ERRORS (normally 100) errors causes a fatal error.
  5416.  
  5417. Error messages which are generated during the compilation pass try to quote
  5418. the source code line apparently responsible (unless the "concise" switch
  5419. is set): but Inform may be unable to do this if the text was read and lost
  5420. too long ago, for example in the case of a "declared but not used" warning.
  5421.  
  5422. Note that informational messages (such as the banner line, the statistics
  5423. printout, etc.) are not routed through "errors.c", or indeed anywhere else.
  5424.  
  5425. Error recovery in Inform is mainly a matter of going into "panic mode"
  5426. (amusingly, this is a term of art in compiler theory): tearing through the
  5427. tokens until a semicolon is reached, then starting afresh with a new
  5428. statement or directive.  This pretty often goes wrong (especially if a
  5429. routine start/end is not noticed), and more work might be needed here.
  5430.  
  5431.  
  5432.    11.4   File input/output
  5433.           -----------------
  5434.  
  5435. The "files.c" section handles almost all of the file input/output in Inform:
  5436. the two exceptions are in cli_interpret() in "inform.c", which loads in ICL
  5437. files; and in link_module() in "linker.c", which loads in modules (a simple
  5438. job which there was no point abstracting).
  5439.  
  5440. The biggest shake-up to this section since Inform 5 was the realisation that,
  5441. far from being a grubby low-level activity, working out good filenames was
  5442. in fact a task which had to be done much higher up in Inform: so all of
  5443. the code which used to do this is now located in the ICL interpreter in
  5444. "inform.c".
  5445.  
  5446. What remains in "files.c" is:
  5447.  
  5448.     opening source code and reading it into buffers;
  5449.     opening and closing the temporary files;
  5450.     calculating the checksum and length of, and then outputting, the
  5451.         story file or module being compiled;
  5452.     opening, writing to and closing the text transcript file;
  5453.     opening, writing to and closing the debugging information file.
  5454.  
  5455. For each different source file that has ever been open, "files.c" maintains
  5456. a structure called FileId, containing the full filename and a file handle.
  5457. The files are never read from except via the routine file_load_chars(),
  5458. which fills up the lexical analyser's buffers.
  5459.  
  5460. The routine output_file() writes the story/module file: see its comments
  5461. for details.  It takes up where construct_storyfile() leaves off, and
  5462. contributes the last two pieces of header data to be worked out, the
  5463. checksum and the length fields.  Note that the checksum calculation is
  5464. only known after the whole file has been written (mainly because Z-code
  5465. backpatching alters the checksum, but can't be done until output time without
  5466. consuming a good deal of extra memory); so that an "fseek" is made to skip
  5467. the write position back into the header and overwrite the correct checksum
  5468. just before closing the file.  This call is made in a strictly ANSI way
  5469. but, like everything on the fringes of the C library-to-operating-system
  5470. interface, may cause trouble on some compilers.
  5471.  
  5472. The other routines are largely self-explanatory.
  5473.  
  5474. There are three temporary files (although they won't be used if -F0 applies),
  5475. as follows:
  5476.  
  5477.     Temporary file         Contents                   
  5478.  
  5479.          1                 The static strings area    
  5480.          2                 The Z-code area            
  5481.          3                 The link data area         (only opened and used
  5482.                                                       in -M, module mode)
  5483.  
  5484. For the format of the debugging information file, see the utility "infact.c",
  5485. which prints from it.  This format is likely to change in the near future
  5486. in any case, as it is already inadequate for some of the new features in
  5487. Inform 6.
  5488.  
  5489.  
  5490.    12   Low-level language features
  5491.         ---------------------------
  5492.  
  5493.    12.1   Using the "Trace" directive
  5494.           ---------------------------
  5495.  
  5496. The trace directive is primarily intended for compiler maintenance purposes.
  5497. It can cause Inform to print tracing information on nine different aspects
  5498. of what it does, in most cases at several levels of detail.
  5499.  
  5500.     -------------------------------------------------------------------------
  5501.     Tracing option        Level        Output
  5502.     -------------------------------------------------------------------------
  5503.     "assembly"            1            all assembly language produced, in
  5504.                                            an imitation of "@..." syntax 
  5505.                           2            and also the actual bytes produced,
  5506.                                            in hexadecimal
  5507.                                        (Note that because trace printing
  5508.                                        occurs before label optimisation,
  5509.                                        addresses of instructions cannot be
  5510.                                        relied on: nor can the values of
  5511.                                        operands which are marked for later
  5512.                                        backpatching.)
  5513.  
  5514.     "tokens"              1            lexemes of all tokens output from the
  5515.                                            lexer to the syntax analyser, and
  5516.                                            indication when a token is put
  5517.                                            back
  5518.                           2            full token descriptions
  5519.                           3            and also the lexical context in which
  5520.                                            they were identified
  5521.  
  5522.     "expressions"         1            annotated parse trees for all
  5523.                                            expressions being code-generated
  5524.                           2            and the behaviour of the shift-reduce
  5525.                                            parser when parsing it, and
  5526.                                            the parse tree received by the
  5527.                                            code generator (not yet annotated)
  5528.                           3            and the token-to-etoken translations
  5529.                                            made, and the parse tree produced
  5530.                                            by the emitter before lvalue
  5531.                                            checking
  5532.  
  5533.     "linker" used in      1            list all import/export information sent
  5534.     compiling module      2            and all marker information sent
  5535.  
  5536.     "linker" used in      1            list all modules linked in
  5537.     compiling story file  2            and all import/export information
  5538.                                            received
  5539.                           3            and all marker information received
  5540.                           4            and how each marker was dealt with
  5541.  
  5542.     "lines"               ---          (currently inoperable)
  5543.     -------------------------------------------------------------------------
  5544.     "dictionary"          1            print current dictionary contents
  5545.                                            (including verb/preposition nos.)
  5546.                                            in alphabetical order
  5547.  
  5548.     "objects"             1            print current object tree
  5549.  
  5550.     "verbs"               1            print current grammar
  5551.  
  5552.     "symbols"             1            print out those entries in the symbols
  5553.                                            table which are not: unknown,
  5554.                                            generated by the veneer or in a
  5555.                                            system file
  5556.                           2            print entire symbols table
  5557.     -------------------------------------------------------------------------
  5558.  
  5559.  
  5560.    12.2   System constants and other secret syntax
  5561.           ----------------------------------------
  5562.  
  5563. The addresses of many important tables in the Z-machine are not recorded
  5564. in the header, or anywhere else: but they are known to the compiler, and
  5565. needed by the run-time code.  The system constants are provided mainly
  5566. as a way of passing this information into run-time code.
  5567.  
  5568.    Constant            Evaluates to
  5569.    --------------------------------------------------------------------------
  5570.    #version_number     Version number of Z-machine format being compiled to
  5571.    #dict_par1          Byte offset in a dictionary table entry of the
  5572.                            the first ("flags") parameter byte
  5573.    #dict_par2          And the second ("verb") byte
  5574.    #dict_par3          And the third ("adjective") byte
  5575.                            (note that these three depend only on the version
  5576.                             number)
  5577.  
  5578.    #largest_object     The largest object number constructed, plus 256
  5579.                            (the "+256" is due to a quirk in the implementation
  5580.                            used by Inform 3 or so; since this constant is not
  5581.                            a very public feature, I don't mind leaving it in)
  5582.  
  5583.    #adjectives_table   Byte addresses of adjectives table,
  5584.    #actions_table                        actions table,
  5585.    #preactions_table                     "preactions table",
  5586.    #classes_table                        class number to object number table,
  5587.    #identifiers_table                    property ID names table
  5588.  
  5589.    #code_offset        Packed address of Z-code area
  5590.    #strings_offset     Packed address of static strings area
  5591.    --------------------------------------------------------------------------
  5592.  
  5593. Two more secret syntaxes were introduced in Inform 6.10.  The first changes
  5594. the behaviour of the "Include" directive:
  5595.  
  5596.    Include "Language__";
  5597.  
  5598. (and no other string) includes the current language definition file, whose
  5599. name is an ICL variable.
  5600.  
  5601. The second controls which grammar table format is generated: normally GV1,
  5602. but this can be set to GV2 by
  5603.  
  5604.    Constant Grammar__Version = 2;
  5605.  
  5606. The "Grammar__Version" symbol is redefinable; if no such Constant directive
  5607. is made, then it will have the value 1.  It needs to be changed to its
  5608. final value before the first Verb, Extend or Fake_Action directive is
  5609. reached.
  5610.  
  5611.  
  5612.    12.3   The "Zcharacter" directive
  5613.           ------------------------
  5614.  
  5615. Finally, the "Zcharacter" directive is provided mostly for the benefit
  5616. of language definition files, for configuring Inform games to use a
  5617. non-English alphabet or character set.  (See the Inform Translator's
  5618. Manual.)  Different forms of "Zcharacter" allow both the Z-machine
  5619. alphabet table and the Unicode translation table to be specified.
  5620.  
  5621.  
  5622. (i) The Z-machine alphabet
  5623.  
  5624. The Z-machine's text encryption system is optimised to make it especially
  5625. cheap on memory to use letters in alphabet 1, then cheapish to use letters
  5626. in alphabets 2 and 3 but rather expensive to use letters which aren't in
  5627. any of the three.  We aren't much concerned about lack of memory in the
  5628. game as a whole, but the economy is very useful in dictionary words,
  5629. because dictionary words are only stored to a "resolution" of nine
  5630. Z-characters.  Thus, in a dictionary word:
  5631.  
  5632.    something from alphabet 1         costs 1 Z-character
  5633.                            2 or 3          2 Z-characters
  5634.              outside the alphabets   costs 4 Z-characters
  5635.  
  5636. The standard arrangement of these alphabets (A1 lower case a to z, A2 upper
  5637. case A to Z, A3 numerals and punctuation marks) includes no accented
  5638. characters.  In a language with frequent accented or non-English letters,
  5639. such as Finnish or French, this means that 4 of the 9 Z-characters in
  5640. a dictionary word may be wasted on just one letter.  For instance,
  5641.  
  5642.    't@'el@'ecarte'    is stored as   't@'el'
  5643.    't@'el@'ephone'    is stored as   't@'el'
  5644.  
  5645. (there are not even enough of the 9 Z-characters left to encode the second
  5646. e-acute, let alone the "c" or the "p" which would distinguish the two words).
  5647. On the other hand if e-acute could be moved into Alphabet 3, say in place of
  5648. one of the punctuation marks which is never needed in dictionary words,
  5649. the two e-acutes would take just 2 Z-characters each and then
  5650.  
  5651.    't@'el@'ecarte'    would be stored as   't@'el@'ecar'
  5652.    't@'el@'ephone'    would be stored as   't@'el@'epho'
  5653.  
  5654. which is far more acceptable.
  5655.  
  5656. The Z-machine has a mechanism (at least in Version 5 or better) for changing
  5657. the standard alphabet tables, invented to make the German translation of
  5658. Infocom's "Zork I" work.  The "Trace dictionary" will print the current
  5659. contents of the alphabet table (as well as the dictionary contents).
  5660.  
  5661.  
  5662. (i).1  Moving a single character in
  5663.  
  5664. There are two ways to change the standard English alphabet table.
  5665. One way, which is probably good enough for a language definition file
  5666. for a mostly Latin language (where only up to around 10 accented or
  5667. non-English letters are commonly needed) is to move characters into
  5668. the least-used positions in Alphabet 2.  For this, use the directive:
  5669.  
  5670.    Zcharacter <char>;
  5671.  
  5672. It will only be possible if there's a letter in A2 which hasn't yet
  5673. been used (otherwise, changing that entry in A2 will make some of the
  5674. text already compiled wrong).  The directive is thus only practicable
  5675. early in compilation, such as at the start of the library definition file.
  5676.  
  5677. For instance the code
  5678.  
  5679.    Trace dictionary;
  5680.    Zcharacter '@'e';
  5681.    Zcharacter '@`a';
  5682.    Zcharacter '@^a';
  5683.    Trace dictionary;
  5684.  
  5685. might produce output including...
  5686.  
  5687. Z-machine alphabet entries:
  5688.  a  b  c (d) e (f) g (h) i  j  k  l  m  n  o (p)(q) r  s  t  u  v (w)(x)(y)(z)
  5689.  A (B) C (D) E (F)(G) H  I (J)(K) L (M)(N) O (P)(Q) R  S (T)(U)(V)(W)(X)(Y)(Z)
  5690. ( ) ^  0  1 (2) 3 (4)(5) 6 (7)(8) 9 (.) , (!)(?)(_)(#)(')(~) / (\) - (:)(()())
  5691.  
  5692. Z-machine alphabet entries:
  5693.  a  b  c (d) e (f) g (h) i  j  k  l  m  n  o (p)(q) r  s  t  u  v (w)(x)(y)(z)
  5694.  A (B) C (D) E (F)(G) H  I (J)(K) L (M)(N) O (P)(Q) R  S (T)(U)(V)(W)(X)(Y)(Z)
  5695. ( ) ^  0  1 @'e 3 @`a@^a 6 (7)(8) 9 (.) , (!)(?)(_)(#)(')(~) / (\) - (:)(()())
  5696.  
  5697. ...in which note that bracketed letters are ones which have not been encoded
  5698. yet.  The three Zcharacter directives have inserted e-acute, a-grave and
  5699. a-circumflex into the positions previously occupied by the numerals 2, 4 and
  5700. 5.  It is reasonable to make up to about 10 such insertions, after which any
  5701. further attempts will only be successful if the game being compiled doesn't
  5702. (let us say) have a title like "123456789: An Interactive Lesson In Counting",
  5703. which would have used 9 of the numerals and forced them to stay in the final
  5704. alphabet table.
  5705.  
  5706.  
  5707. (i).2  Changing the entire alphabet
  5708.  
  5709. This has to be done very early in compilation, before any strings are
  5710. translated, so that it can't be done by a language definition file.
  5711. One might put such directives into a file called "Alphabet.inf" and
  5712. then begin the main game with
  5713.  
  5714.    Include "Alphabet";
  5715.  
  5716. to achieve this.
  5717.  
  5718. The form required is to give three strings after "Zcharacter", containing
  5719. 26, 26 and 23 characters respectively.  For instance:
  5720.  
  5721.    Zcharacter "abcdefghijklmnopqrstuvwxyz"
  5722.               "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  5723.               "0123456789!$&*():;.,<>@{386}";
  5724.  
  5725. (Note that "@{386}" specifies only one character: Unicode $0386.)  Space,
  5726. new-line and quotation marks " are automatically included, while
  5727. ~, @ and ^ have special meanings in Inform and should not be used.
  5728. Otherwise, any arrangement of characters is fine, except that every
  5729. character used has to be either a normal ASCII character or part of
  5730. the "extra characters" (already declared) in the ZSCII set.
  5731.  
  5732.  
  5733. (ii)  Defining the "extra characters"
  5734.  
  5735. Inform normally makes up a block of "extra characters" based on the
  5736. source code it reads: if it reads plain ASCII or ISO Latin1 (-C0 or
  5737. -C1) then the block contains the usual European accents, such as
  5738. e-acute or i-circumflex, as defined in Z-machine Standard 0.2.  (And
  5739. if this table is never changed, Inform doesn't then compile the
  5740. table at all, as this is the default Z-machine arrangement.)
  5741.  
  5742. More generally if Inform reads ISO 8859-n (-Cn) then the block is set
  5743. up to contain all the non-ASCII letter characters in ISO 8859-n.
  5744.  
  5745. There's room to spare for others to be added, and
  5746.  
  5747.    Zcharacter table + '@{386}';
  5748.  
  5749. would add Unicode character $0386 (Greek capital Alpha with tonos
  5750. accent, as it happens) to the current stock of "extra characters".
  5751.  
  5752. Alternatively, you can simply give a fresh stock altogether:
  5753.  
  5754.    Zcharacter table '@{9a}' '@{386}' '@^a';
  5755.  
  5756. would specify a stock of just three, for instance.
  5757.  
  5758. These directives must be made before the characters in question are
  5759. first used in game text.
  5760.  
  5761.  
  5762.    12.4   Sequence points
  5763.           ---------------
  5764.  
  5765. Inform marks certain positions in the code it compiles as being
  5766. "sequence points".  The idea is that the code can be regarded as a
  5767. sequence of chunks, and the sequence points mark where these chunks
  5768. begin.  Roughly speaking, each different statement in Inform source code
  5769. compiles to a different chunk, so that statements correspond closely to
  5770. sequence points.  Sequence points are marked in assembly trace output
  5771. using the notation "<*>".  For instance, the source code
  5772.  
  5773.     [ WorkOutSquares counter;
  5774.       counter = 0;
  5775.       while (counter < 100)
  5776.       {   squares-->counter = counter*counter;
  5777.           counter = counter + 1;
  5778.       }
  5779.     ];
  5780.  
  5781. produces the traced output:
  5782.  
  5783.     6  +00008  [ WorkOutSquares counter 
  5784.  
  5785.     7  +00009 <*> store        counter short_0 
  5786.     8  +0000c    .L0
  5787.     8  +0000c <*> jl           counter short_100 to L1 if FALSE
  5788.     9  +00011 <*> mul          counter counter -> sp 
  5789.     9  +00015     storew       long_480 counter sp 
  5790.    10  +0001b <*> add          counter short_1 -> counter 
  5791.    11  +0001f     jump         L0 
  5792.    11  +00022    .L1
  5793.    12  +00022     rtrue        
  5794.  
  5795. The "<*>" in front of an instruction means "the position where this
  5796. instruction begins is a sequence point".  We could mark the four
  5797. positions in the original source code as:
  5798.  
  5799.     [ WorkOutSquares counter;
  5800.       <*> counter = 0;
  5801.       <*> while (counter < 100)
  5802.       {   <*> squares-->counter = counter*counter;
  5803.           <*> counter = counter + 1;
  5804.       }
  5805.     ];
  5806.  
  5807. Note that the open and close braces and square brackets don't normally
  5808. cause sequence points.  The exact rule is that every statement,
  5809. action < > command, assignment or expression in void context is at
  5810. a sequence point, except as shown in the examples below:
  5811.  
  5812.     for (<*> i=0: <*> i<45: <*> i++) ...
  5813.  
  5814. "for" loops contain 0 to 3 sequence points, depending on whether there's
  5815. any code compiled in the three parts of the specification.  For instance
  5816.  
  5817.     for (::) <*> print "Madness!";
  5818.  
  5819. contains no sequence point corresponding to the "for" specification.
  5820.  
  5821.     <*> objectloop (<*> O ofclass Coin) <*> print (name) O;
  5822.  
  5823. "objectloop" normally generates two sequence points: at the start,
  5824. where the variable is initialised, and then where it's tested.  However,
  5825. loops over the contents of particular objects work differently:
  5826.  
  5827.     <*> objectloop (O in Mailbox) <*> print (name) O;
  5828.  
  5829. (Because the test "O in Mailbox" is not actually being performed at
  5830. run-time: instead, O is looping through the tree.)
  5831.  
  5832.     do <*> print counter++, " "; <*> until (counter < 17);
  5833.  
  5834. Here the sequence point generated by the loop itself is attached to
  5835. the "until" clause, not the "do" clause, because that's where the
  5836. test is performed.
  5837.  
  5838.  
  5839. "switch", "while" and "if" statements are not exceptions to the
  5840. usual rule (1 statement = 1 sequence point at the beginning), but it
  5841. might be useful to give some examples anyway:
  5842.  
  5843.     <*> switch(counter)
  5844.     {   1: <*> print "One^";
  5845.         2, 3: <*> print "Two or three^";
  5846.         default: <*> print "Neither^";
  5847.     }
  5848.  
  5849.     <*> if (i == 17) <*> print "i is 17"; else <*> print "i isn't 17";
  5850.  
  5851.     <*> while (i<100) <*> print i++;
  5852.  
  5853.  
  5854. The following is true:
  5855.        Except possibly in code explicitly assembled using the "@"
  5856.            notation, at each sequence point the Z-machine stack
  5857.            is empty and no important information is held in the
  5858.            global variables reserved by Inform as "registers":
  5859.            thus, it's safe for a debugger to switch execution from
  5860.            any sequence point in a routine to any other.
  5861.        No two sequence points can be at the same position in either
  5862.            the source code or the compiled code.
  5863.        Every sequence point corresponds to a definite position in the
  5864.            source code (because the veneer, i.e. the code compiled
  5865.            from within Inform itself, contains no sequence points).
  5866.  
  5867. But the following is _not_ true:
  5868.        Sequence points occur in the same order in the source code
  5869.            as they do in compiled code
  5870.        Every routine contains at least one sequence point
  5871.  
  5872. Inform uses sequence points only to generate debugging information
  5873. files for Infix, and to annotate assembly tracing output.  They do not
  5874. affect the code compiled.
  5875.  
  5876.  
  5877.    12.5   Format of debugging information files (for Infix)
  5878.           -------------------------------------------------
  5879.  
  5880. This is a provisional specification of a format which will probably
  5881. change slightly in future releases.  Support for the old -k option has
  5882. been re-introduced in Inform 6.12 to assist development of Infix, the
  5883. projected source-level debugger for Inform.  (See the minor utility
  5884. program "infact", updated to 6.12 format, which prints out the contents
  5885. of a debugging information file in legible form.)
  5886.  
  5887. A debugging information file begins with a six-byte header:
  5888.  
  5889.   0,1  the bytes $DE and then $BF (DEBF = "Debugging File")
  5890.   2,3  a word giving the version number of the format used (currently 0)
  5891.   4,5  a word giving the current Inform version number, in its
  5892.            traditional decimal form: e.g. 1612 means "6.12"
  5893.  
  5894. The remainder of the file consists of a sequence of records, terminated
  5895. by an end-of-file record.  These records may be in _any_ order unless
  5896. otherwise noted.  Each record begins with an identifying byte, for which
  5897. constants looking like *_DBR are defined in Inform's source code.
  5898.  
  5899. A "string" is a null-terminated string of ASCII chars.
  5900. A "word" is a 16-bit unsigned number, high byte first.
  5901. A "line" is a sequence of four bytes: the first is the file number,
  5902.    the next two are a line number (a word), and the last is a character
  5903.    number within that line.
  5904.    In all three cases -- file numbers, line numbers, character numbers --
  5905.    counting begins at 1.  The line reference 0:0:0 is however used to
  5906.    mean "no such line": for instance, the metaclass "Routine" is defined
  5907.    at line 0:0:0, because it's defined by the compiler, not in any
  5908.    source code.
  5909.    Character positions greater than 255 in any line are recorded simply
  5910.    as 255.
  5911. An "address" is a 24-bit unsigned number, a sequence of three bytes
  5912.    (high byte, middle byte, low byte).  All addresses are counted in
  5913.    bytes (rather than being Z-machine packed addresses).
  5914.  
  5915.    EOF_DBR   (byte: 0)
  5916.    End of the debugging file.
  5917.  
  5918.    FILE_DBR   (byte: 1)
  5919.    <file number>         1 byte, counting from 1
  5920.    <include name>        string
  5921.    <actual file name>    string
  5922.    One of these records always appears before any reference to the
  5923.    source code file in question.
  5924.  
  5925.    CLASS_DBR   (byte: 2)
  5926.    <name>                string
  5927.    <defn start>          line
  5928.    <defn end>            line
  5929.  
  5930.    OBJECT_DBR   (byte: 3)
  5931.    <number>              word
  5932.    <name>                string
  5933.    <defn start>          line
  5934.    <defn end>            line
  5935.  
  5936.    GLOBAL_DBR   (byte: 4)
  5937.    <number>              byte
  5938.    <name>                string
  5939.  
  5940.    ARRAY_DBR   (byte: 12)
  5941.    <byte address>        word
  5942.    <name>                string
  5943.    The byte address is an offset within the "array space" area, which
  5944.    always begins with the 480 bytes storing the values of the global
  5945.    variables.
  5946.  
  5947.    ATTR_DBR   (byte: 5)
  5948.    <number>              word
  5949.    <name>                string
  5950.  
  5951.    PROP_DBR   (byte: 6)
  5952.    <number>              word
  5953.    <name>                string
  5954.  
  5955.    FAKE_ACTION_DBR   (byte: 7)
  5956.    <number>              word
  5957.    <name>                string
  5958.    Note that the numbering of fake actions differs in Grammar Versions
  5959.    1 and 2.
  5960.  
  5961.    ACTION_DBR   (byte: 8)
  5962.    <number>              word
  5963.    <name>                string
  5964.  
  5965.    HEADER_DBR   (byte: 9)
  5966.    <the header>          64 bytes
  5967.    This is provided in order to check that a debugging information file
  5968.    (probably) does match a given story file.
  5969.  
  5970.    ROUTINE_DBR   (byte: 11)
  5971.    <routine number>      word
  5972.    <defn start>          line
  5973.    <PC start>            address
  5974.    <name>                string
  5975.    then for each local variable:
  5976.    <local name>          string
  5977.    terminated by a zero byte.
  5978.    Note that the PC start address is in bytes, relative to the start of
  5979.    the story file's code area.  Routines are numbered upward from 0,
  5980.    and in each case the ROUTINE_DBR, LINEREF_DBR and ROUTINE_END_DBR
  5981.    records occur in order.
  5982.  
  5983.    LINEREF_DBR   (byte: 10)
  5984.    <routine number>              word
  5985.    <number of sequence points>   word
  5986.    and then, for each sequence point:
  5987.    <source code position>        line
  5988.    <PC offset>                   word
  5989.    The PC offset for each sequence point is in bytes, from the start of the
  5990.    routine.  (Note that the initial byte of the routine, giving the number
  5991.    of local variables for that routine, is at PC offset 0: thus the actual
  5992.    code begins at PC offset 1.)  It is possible for a routine to have no
  5993.    sequence points (as in the veneer, or in the case of code reading simply
  5994.    "[; ];").
  5995.  
  5996.    ROUTINE_END_DBR   (byte: 14)
  5997.    <routine number>      word
  5998.    <defn end>            line
  5999.    <next PC value>       address
  6000.  
  6001.    MAP_DBR   (byte: 13)
  6002.    A sequence of records consisting of:
  6003.    <name of structure>   string
  6004.    <location>            address
  6005.    terminated by a zero byte.
  6006.    The current names of structures consist of:
  6007.        "abbreviations table"
  6008.        "header extension"
  6009.        "alphabets table"
  6010.        "Unicode table"
  6011.        "property defaults"
  6012.        "object tree"
  6013.        "common properties"
  6014.        "class numbers"
  6015.        "individual properties"
  6016.        "global variables"
  6017.        "array space"
  6018.        "grammar table"
  6019.        "actions table"
  6020.        "parsing routines"
  6021.        "adjectives table"
  6022.        "dictionary"
  6023.        "code area"
  6024.        "strings area"
  6025.    Other names made be added later, and some of the above won't be
  6026.    present in all files ("Unicode table", for instance).  Locations are
  6027.    byte addresses inside the story file.
  6028.  
  6029. LINEREF_DBR records will probably be compressed in future releases.
  6030.  
  6031.  
  6032.    13   What little I remember
  6033.         ----------------------
  6034.  
  6035.    13.1   Publication history
  6036.           -------------------
  6037.  
  6038. The language has existed in the following different forms on the Internet:
  6039.  
  6040.       zass                   (never publically released)
  6041.       Inform 1      v0.5     April 30th 1993
  6042.       Inform 2      v0.6     (I can't find any record of this date)
  6043.       Inform 3      v1.0     November 17th 1993
  6044.       Inform 3a              December 7th 1993
  6045.       Inform 4               January 20th 1994
  6046.       Inform 5               June 1st 1994
  6047.       Inform 5.1             June 12th 1994
  6048.       Inform 5.2             June 19th 1994
  6049.       Inform 5.3             (released on an "Acorn User" cover disc)
  6050.       Inform 5.4             October 2nd 1994
  6051.                    update    later in October 1994
  6052.       Inform 5.5    v1501    late May/early June (private circulation)
  6053.                     v1502    June 30th 1995
  6054.       Inform 6      v6.01    April 30th 1996: declared a "beta" release
  6055.                     v6.02    May 5th 1996
  6056.                     v6.03    May 10th 1996
  6057.                     v6.04    September 12th 1996: declared no longer "beta"
  6058.                     v6.05    September 24th 1996
  6059.       Inform 6.1    v6.10    December 16th 1996
  6060.                     v6.11    January 27th 1997
  6061.                     v6.12    March 26th 1997
  6062.                     v6.13    April 5th 1997
  6063.                     v6.14    September 8th 1997
  6064.  
  6065. There have been a few other very slightly modified states, consisting of
  6066. bug fixes and source code portability improvements on the above (e.g.
  6067. Inform 4 went through a fairly long process of tidying-up once it reached
  6068. the porters); and a number of CD ROM releases.  But these are insignificant
  6069. from a language design point of view and were unnoticed by "the public",
  6070. i.e., by Inform's base of users.
  6071.  
  6072. This base of users has continuously grown, from size 1 (myself) to what at
  6073. time of writing is a very large group of at least casual users and a group of
  6074. perhaps 30 "serious" ones whom I actually know.  Inform's early versions were
  6075. very hard to use (as will become clear), and as a language it only attracted
  6076. attention because:
  6077.  
  6078.    (a) it did something undeniably "cool", as aficionados of 1980s adventure
  6079.        games mostly agree - it revived the Infocom run-time format,
  6080.        and the early Inform manuals were for a while the fullest documents
  6081.        on the Web describing the Infocom format; and
  6082.    (b) since "Curses" had been written in it, the compiler must at least work.
  6083.        (Even though the source code for "Curses" has never been made public,
  6084.        the fact that it was known to exist underwrote the project and made
  6085.        it seem worthwhile to the many porters who invested considerable time
  6086.        and effort on initially complex and poorly written code.)
  6087.  
  6088. I first posted Inform to the Internet in the spirit of "glasnost" rather than
  6089. with any pretension that it would be a widely used program.  (It worked for
  6090. me, which was all that was then required.)  By mid-1994 my ambitions for it
  6091. had grown: in looking back, that first year is the interesting one.
  6092.  
  6093.  
  6094.    13.2   Design history
  6095.           --------------
  6096.  
  6097. Inform was designed specifically as a language to express programs which
  6098. would run on the Z-machine, a run-time format which already existed.  In
  6099. turn, the Z-machine was designed specifically as a run-time format for
  6100. an existing language (ZIL, or Zork Implementation Language, a form of MDL).
  6101. Inform is therefore the result of a game of Chinese whispers, since I had no
  6102. idea what ZIL looked like until much later.
  6103.  
  6104. In fact Inform and ZIL are entirely dissimilar.  One reason for this is that
  6105. ZIL is syntactically a very high-level language, not unlike LISP, and its
  6106. compiler (ZILCH) made a substantial translation down to Z-machine level:
  6107. whereas Inform was designed very close to the Z-machine level.  It is often
  6108. remarked that Inform resembles C, and although this is partly because some
  6109. syntax conventions were borrowed from C by a designer who felt comfortable
  6110. with it, another reason is that both languages were designed for easy
  6111. translation to efficient low-level code.
  6112.  
  6113. Inform began as an assembler called "zass", whose syntax continues to exert
  6114. a (perhaps malign) influence on the language of today.  The zass assembly
  6115. mnemonics were different from the modern set (this was at a time when no
  6116. standardisation of opcode names had taken place), and were copied from the
  6117. set of names output by Mark Howell's disassembler "txd".  (The opcode
  6118. names recognised by Inform were tinkered with until Inform 5 when the standard
  6119. set was agreed.)  But the format of routines and labels remains.  A typical
  6120. "zass" routine looked like this:
  6121.  
  6122.     [ Routine v1 v2 ... vn
  6123.       an assembly line
  6124.       .alabel
  6125.       another assembly line
  6126.     ]
  6127.  
  6128. and semicolons were introduced as line separators when "zass" became Inform
  6129. 1.  Individual assembly lines then took the form
  6130.  
  6131.     opcode operand1 ... operandn store;
  6132.  
  6133. (if they were store operands), with no syntactic indication that the last
  6134. operand was not really an operand but a store destination.  This persisted
  6135. until Inform 5, and is still recognised in Inform 6, though the preferred
  6136. syntax is now
  6137.  
  6138.     opcode operand1 ... operandn -> store;
  6139.  
  6140. Right up until Inform 5, similarly, "sp" was a reserved word meaning "the
  6141. assembly-language stack pointer", preventing its use as a local variable
  6142. name (for example).  Only in Inform 6 has it disappeared from the set of
  6143. reserved words (except in the context of assembly lines).
  6144.  
  6145. One of the most unusual features of Inform is its handling of local variables
  6146. to functions, in that
  6147.  
  6148.     (a) functions can be called with any number of arguments;
  6149.     (b) there's no specification by the programmer of any expected number
  6150.         of arguments;
  6151.     (c) local variables and argument-receiving variables are treated as
  6152.         the same;
  6153.     (d) there are at most 15 local variables per routine.
  6154.  
  6155. All four arise from the fact that this is how Z-machine programs behave:
  6156. these were the rules for zass, and they're still the rules for Inform 6.
  6157. It's efficient to identify Inform's idea of local variables with the
  6158. Z-machine implementation of locals; nevertheless, the decision to do so
  6159. was made by default.
  6160.  
  6161. This illustrates a general point about restrictions in the Inform syntax.
  6162. The Z-machine is rich, well-equipped with features making it a good target
  6163. for compilation.  It implements, let us say, feature F subject to a modest
  6164. restriction (for example, it implements local variables subject to a limit
  6165. of 15 per routine).  Since this is good enough for most purposes, and
  6166. efficient, and easy to compile to, an early release of Inform decided to
  6167. make use of the Z-machine's implementation directly; and consequently the
  6168. design of the Inform language was shaped around the restriction needed
  6169. to make it possible to use F.
  6170.  
  6171. In other words, if a sparer "RISC" target machine had been chosen, Inform
  6172. would have been obliged to make a new implementation of feature F, which
  6173. would not have been subject to arbitrary Z-machine restrictions.
  6174.  
  6175. Perversely, it is therefore Inform's greatest weakness (as well as its
  6176. greatest selling point) that it compiles to the Z-machine.  At least, though,
  6177. there is a not inconsiderable reward from using the Z-machine's features
  6178. so directly: compact and fast code results.
  6179.  
  6180. In any case, the history of Inform is a continuous process of syntax moving
  6181. away from direct expression of the Z-machine and towards a higher-level
  6182. description of a program.
  6183.  
  6184.  
  6185. Something that partially frustrated this was that Inform acquired a serious
  6186. user base "too soon", before the language design was mature enough: by Inform
  6187. 4, a good many people were using Inform, and this began to make me nervous of
  6188. changing the established syntax. But if a syntax feature is clearly "wrong"
  6189. (that is, anomalous and inconvenient) then clearly one must bite the bullet
  6190. and make a change.  In retrospect, I feel I have always been too hesitant
  6191. over this.
  6192.  
  6193. For example, I realised when working on Inform 5.1 that the notation
  6194.  
  6195.     print "You swallow ", (the) food, " with glee.";
  6196.  
  6197. to mean "print the name of the object whose number follows, preceding it
  6198. by a suitable definite article", would be desirable.  But I had wanted
  6199. Inform 5 to be a point of stability, not rapid change, and so I shied away
  6200. from adding this feature (besides, I was worried about complicating the
  6201. interaction between the library and the language itself).  I did not in fact
  6202. add the feature until Inform 5.5, but it would have been easier for all
  6203. concerned had I done so earlier.
  6204.  
  6205. The moral to draw would be that any really big changes still needed ought
  6206. to be made now.  Unfortunately, they are just too big (the syntax for
  6207. character and dictionary literals, for example, or for array and property
  6208. value initialisation) and so I have failed to learn my lesson, after all.
  6209.  
  6210.  
  6211. Another problem with an evolutionary design is that vestigial features tend
  6212. to survive, especially if one is trying to serve a user base who may still
  6213. be using old syntaxes.  (For instance, using old library files of code.)
  6214. A problem P, say, is given a crude solution S1 in 1993, a slightly better
  6215. solution S2 in 1994 and a proper solution S3 in 1995.  By this time, does
  6216. Inform still have to recognise the syntaxes applying to S2 and S1?  Usually
  6217. I have decided to make it do so; the formal concept of an "obsolete usage"
  6218. (which would be recognised but cause "please change this" warnings to be
  6219. issued) was not added to Inform until 5.5.
  6220.  
  6221. For example, how do we set a property value?  In Inform 1, by using a line
  6222. of assembly code:
  6223.  
  6224.     put_prop lamp oil_left 15;
  6225.  
  6226. By Inform 3 this had become painful, and a shift away from assembly language
  6227. was taking place, but not a drastic one.  The statement "write" was devised
  6228. for writing a sequence of property values (in this example, just one):
  6229.  
  6230.     write lamp oil_left 15;
  6231.  
  6232. (Even this existed partly because of a horrid form of "object recycling"
  6233. present in Autumn 1993 forms of "Curses" and very early drafts of "Jigsaw",
  6234. causing objects to be heavily over-written: it became necessary to change
  6235. many properties in one go.  The "write" statement was a great help.)
  6236.  
  6237. Only in Inform 4 did the C-like form appear:
  6238.  
  6239.     lamp.oil_left = 15;
  6240.  
  6241. And not until Inform 6 was it possible to apply ++ and -- to a property
  6242. specified in this way.  Likewise, only in Inform 6 was the "write" statement
  6243. finally withdrawn from recognition, though it was flagged as obsolete in
  6244. Inform 5.5.
  6245.  
  6246. Such obsolete syntaxes do not merely increase the "clutteredness" of the
  6247. language; they also block more desirable syntaxes by causing clashes.  And
  6248. the tendency to provide partial solutions to problems has been unfortunate
  6249. in putting off the point where significant change is needed.  I did not
  6250. realise in "zass" that a notation was needed to refer to dictionary words
  6251. as operands of opcodes, automatically creating them if need be; then I did
  6252. realise this, in Inform 1, but made a directive called "Dictionary" to set
  6253. constant symbol names equal to their dictionary addresses; in Inform 3,
  6254. I found this was cumbersome and instead used the syntax #n$... to indicate
  6255. "new dictionary word" (it seemed logical since #w$... was being used for
  6256. "existing dictionary word"); in Inform 5, the syntax '...' was used, and
  6257. this was perhaps a mistake, since it clashes slightly with the syntax for
  6258. specifying literal characters.
  6259.  
  6260. If I had realised at Inform 1 that a syntax was needed, this would have been
  6261. avoided.  As a footnote, #n$... is still present in the language; #w$...
  6262. and "Dictionary" were finally deleted in Inform 6.
  6263.  
  6264.  
  6265. A happier point of view on this evolution is that, at every stage, the subset
  6266. of Z-machine features which Inform could use expanded.  Inform 1 could produce
  6267. only version 3 games; Inform 4 was a major breakthrough in making version 5
  6268. games; and so on.  (V5 did not become the default version compiled to
  6269. until Inform 5, but this reflects a lack of confidence in the interpreters
  6270. for high-version-number Z-machines then available.)  And an evolved syntax
  6271. is at least adapted to what its users want of it.
  6272.  
  6273.  
  6274.     (i)  Inform 1 and 2
  6275.          --------------
  6276.  
  6277. Inform 1, then, was the assembler "zass" rewritten and with certain shorthands
  6278. added.  For example,
  6279.  
  6280.     var = number operator number;
  6281.  
  6282. was permitted, though full expressions were not.  Most of the "creating"
  6283. directives were present -- Object, Global, Property and Attribute -- though
  6284. directives were not syntactically distinguished from statements, and could
  6285. be mixed freely.  Nor were statements distinguished from assembly lines:
  6286. indeed, most of them were assembly lines.
  6287.  
  6288. In addition, control structures were provided:
  6289.  
  6290.      if ... else ...
  6291.      while ... ...
  6292.      do ... until ...
  6293.  
  6294. These took their modern form, except that conditions did not need to be
  6295. bracketed, and braces were compulsory around all code blocks, even those
  6296. which contained only one statement.  A form of "for" loop was provided,
  6297. but took the BASIC-like form "for var 1 to 10".  (This syntax existed
  6298. alongside the modern "for" syntax until Inform 6.)
  6299.  
  6300. Grammar and actions existed in their modern form from the first (except
  6301. for the <...>, <<...>> notation for causing them).  Object definitions took
  6302. their modern form (except that specifying a parent was compulsory, there was
  6303. no "class" segment and routines could not be given as property values).
  6304.  
  6305. And that was about all.  The language appears from this description to be
  6306. very primitive, and it was, but it was not so different in appearance from a
  6307. "real" language (except for the lack of compound expressions) and "Curses"
  6308. was written in Inform 1 code for about two years before being translated
  6309. into modern syntax.
  6310.  
  6311. Inform 2 was only a tidying-up release of Inform 1.
  6312.  
  6313.  
  6314.     (ii)  Inform 3 and 3a
  6315.           ---------------
  6316.  
  6317. Inform 3 was a more substantial upgrade, with various worthy features
  6318. (command line switches; control over header flag bits) added.  But the
  6319. driving force was that "Curses" was being expanded, and running severely into
  6320. the limits of the Z-machine Version 3 architecture: in particular, the limit
  6321. of 255 objects.  "Curses" apparently needed a minimum of about 270: Richard
  6322. Tucker suggested to me that there was no need for the 255 physical Z-machine
  6323. objects to correspond directly to the 270 game objects.  So the idea of
  6324. "recycling" was born.  Object O might be a carpet in one room and a door in
  6325. another: as long as it was impossible for these ever to be simultaneously
  6326. present.  When either room was entered, everything about O was over-written
  6327. to make it the appropriate definition.
  6328.  
  6329. This made it necessary to be able to drastically alter objects.  The "write"
  6330. statement (see above) was introduced to fix properties, a syntax #n$...
  6331. was introduced to refer to dictionary words (because so many were needed as
  6332. property values to over-write with) and the @.. string escape was added
  6333. to make use of the Z-machine's abbreviations table, with the "string"
  6334. statement added for changing entries in it.  (This last made it possible for
  6335. the apparently unalterable object short-name to consist of a string reading
  6336. "print abbreviation 1", so that by changing abbreviation 1 it was possible to
  6337. effectively alter short names.)  Finally, object declaration syntax was
  6338. altered to make it possible to give the same object more than one symbol
  6339. name.
  6340.  
  6341. In retrospect this substantial effort to break the game-object Z-object
  6342. correspondence was misguided; the proper solution to the problem was to make 
  6343. Inform Version-5 capable (as happened in Inform 4).  It ought to be
  6344. remembered, though, that at this time many people were using Version 3
  6345. interpreters not capable of running Version 5 games (indeed, the Version 5
  6346. release of "Curses" was one of the nudges towards a wider awareness of
  6347. Version 5 and the interpreters capable of running it).  Inform hung back
  6348. because interpreters were not ready; yet as events turned out, interpreters
  6349. became ready partly because of Inform overtaking them.
  6350.  
  6351. Inform 3a was a tidying-up release of Inform 3.
  6352.  
  6353.  
  6354.     (iii)  Inform 4
  6355.            --------
  6356.  
  6357. Inform truly became a high-level language, rather than an assembler with
  6358. delusions of grandeur, only with the release of Inform 4.
  6359.  
  6360. The important new addition was a full expression evaluator, recognising
  6361. operators (and an expanded set of these, including for instance ++ and --),
  6362. precedence levels, brackets and so on.  Conditions were also permitted to
  6363. be compound, using the new logical operators && and ||.  Properties could
  6364. be referred to using the new "." operator (along with ".&" and ".#").
  6365. System functions (such as "children" and "random") were added.
  6366.  
  6367. This was the decisive break of the correspondence between Inform statements
  6368. and Z-machine instructions: expressions no longer looked like three-address
  6369. code by any other name, and might compile to arbitrarily long sequences of
  6370. instructions.  Opcodes like "random" were no longer accessed directly, but
  6371. via system functions.
  6372.  
  6373. The most annoying syntax point remaining was that braces were still
  6374. compulsory.  A typical Inform 3 line might have been:
  6375.  
  6376.     if i == 2 { print "Two"; }
  6377.  
  6378. This restriction was now lifted.  Implementation considerations
  6379. (specifically, in the source line-reader which fed into the tokeniser) meant
  6380. that some indication was needed of where the condition ended, and so brackets
  6381. were imposed on conditions.  Thus, the corresponding Inform 4 line:
  6382.  
  6383.     if (i == 2) print "Two";
  6384.  
  6385. Making the parallel with C even closer, new-style "for" loops were
  6386. introduced:
  6387.  
  6388.     for (i=0:i<10:i++) print i;
  6389.  
  6390. (and the desire to make Inform capable of compiling "for" loops as complex as
  6391. those available to C caused the operators ++, -- and , to be added).  More
  6392. originally, "objectloop" was added.
  6393.  
  6394. Although it had little impact on the syntax, to the outside world the major
  6395. development was that Inform was now capable of compiling Version 5 files
  6396. (which had no limit on object numbers and could be twice as large as Version
  6397. 3 ones).  The main impact of this on the language (which I now regret) was
  6398. that statements like "box" and "style" were added to control newly available
  6399. text features of the Z-machine.
  6400.  
  6401. Otherwise I took the decision that in principle all Inform programs should be
  6402. cross-compilable to all versions (subject to the limits applying in each
  6403. version), and this remains substantially true.  Since certain game operations
  6404. such as saving, loading and reading the keyboard were commanded by very
  6405. different assembly language in versions 3 and 5, these were abstracted into
  6406. statements so that, for instance, what looked like version-3 assembly
  6407. language to read the keyboard would in fact be compiled to appropriate but
  6408. different version-5 assembly.
  6409.  
  6410.  
  6411.     (iv)  Inform 5
  6412.           --------
  6413.  
  6414. The final stage in Inform's arrival as a programming language took place a
  6415. little over a year after Inform 1's creation.  Only then did I look back in
  6416. leisure at the language, and only then did I begin to seriously find out about
  6417. the rival adventure-game languages to see what they were capable of.  I was
  6418. unimpressed except by TADS (which I continue to have a great respect for):
  6419. the point was rubbed home when I was adapting the original mainframe
  6420. Adventure, "Colossal Cave", to Inform for use as an example.  Dave Baggett's
  6421. TADS translation was constantly at my side, and it became obvious that the
  6422. corresponding Inform 4 code was far less legible.
  6423.  
  6424. In some ways, then, the Inform 5 syntax was worked out by constructing the
  6425. language so as to make the implementation of "Advent" look neat.
  6426.  
  6427. Although Inform had, from the first, associated code closely with objects
  6428. (the concept of before/after routines was part of the original conception),
  6429. only now was this brought out in syntax by making explicit routine definitions
  6430. property values.  (Previous code had been full of property values like
  6431. "FireplacePre", which were names of what would now be called before-routines.)
  6432. The syntax now seems obvious and natural, but at the time it felt like a
  6433. breakthrough: what had been broken through, I think, was the residual feeling
  6434. that Inform was an assembler at heart, whose programs were a list of routines
  6435. interspersed with some overgrown variable definitions.
  6436.  
  6437. Class definitions (and the inheritance rules) followed in the same, somewhat
  6438. bewildering, couple of days, and a brace of aesthetic changes followed:
  6439. dictionary words written 'thus', ##Names for actions (rather than the
  6440. previous #a$Name syntax), the use of bare strings as implied "print_ret"
  6441. statements. Most importantly, the use of <...> and <<...>> to trigger
  6442. actions, and the implementation of what amounted to a switch statement on the
  6443. current action within embedded routines.
  6444.  
  6445. I have come to realise that adventure game programs are unusually dense in
  6446. selections and comparison against lists of alternative possibilities.  Inform
  6447. now contains many syntaxes to make such comparisons concise:
  6448.  
  6449.     switching on actions in embedded routines;
  6450.     the "switch" statement (added in Inform 5.5) - note that both of these
  6451.         deliberately take a more concise form from, say, C, by not allowing
  6452.         case fall-through and therefore not requiring the incessant use
  6453.         of "break" statements;
  6454.     switch ranges such as "5, 7, 8 to 19: ...";
  6455.     the "or" alternative operator in conditions, as in "if (x == 1 or 5) ...".
  6456.  
  6457. And this, I feel, is something for which I should make no apology.
  6458.  
  6459. Later developments (in 5.5) included the Array directive (previously, it was
  6460. customary to use global variables to point to arrays) and the printing
  6461. syntaxes for "print (The) ..." and so forth (see above).  An extension was
  6462. made to "Versions 7 and 8" (new hybrids of the Z-machine allowing larger
  6463. games to be compiled), though this had little impact on the language or the
  6464. compiler.
  6465.  
  6466. The release of Inform 5.5 notwithstanding, the language remained essentially
  6467. stable during the two years between Inform 5 and Inform 6.  For the first
  6468. time it became possible for people other than myself to seriously use Inform,
  6469. rather than toy with it.  From Inform 5 onwards, the issue has not been
  6470. adequacy of the language but adequacy of its documentation, and I think this
  6471. is the point where Inform can be counted a "proper" language.
  6472.  
  6473.  
  6474.    13.3   Implementation history
  6475.           ----------------------
  6476.  
  6477. Writing a compiler for a large language from scratch requires glacial
  6478. patience, but the result is a mountain.  The time invested in tedious details
  6479. during development is repaid ten times over when the compiler comes to be
  6480. used.  Temporary measures are infernal temptations, and must be rejected
  6481. firmly.
  6482.  
  6483. Inform was not written this way.
  6484.  
  6485. The compiler has been through three "design iterations": "zass", which was
  6486. discarded as soon as I thought I had understood how the Z-machine worked,
  6487. Inform 1 to 5.5, and now Inform 6.  This section briefly describes the second
  6488. iteration.
  6489.  
  6490. Inform 1 was essentially a program for translating assembly language lines
  6491. into Z-code statements.  It made the generous and unjustified assumption
  6492. that its input would always be well-formed except for the odd spelling
  6493. mistake, and did not check syntax particularly carefully: lexical analysis
  6494. consisted of grabbing a line from the source code files (accessing these
  6495. files a byte at a time, in an unbuffered way) and cutting out white space
  6496. to leave a set of tokens.  Syntax analysis consisted of going through
  6497. these tokens until a line seemed to have worked out all right, and then
  6498. forgetting the line altogether (never checking if there were any more tokens).
  6499. This caused an enormous number of little jobs later, testing for error
  6500. conditions like "expected a semicolon after ... but found ..." in a quite
  6501. unsystematic way.
  6502.  
  6503. Not only was there no formal apparatus for syntax analysis, but lexical
  6504. analysis went on all over the place, with strings being cut up and compared
  6505. against the symbols table erratically (and often repeatedly).  Tokens were
  6506. stored as strings (with all the consequent inefficiencies of manipulation).
  6507. Direct string comparisons were commonplace, making it difficult to pin down
  6508. what the set of reserved words was, and indeed almost impossible to write
  6509. a precise definition of what programs would pass Inform syntax checking.
  6510.  
  6511. When statements required translation into code, this translation would
  6512. actually be made into textual assembly language instructions, fed back into
  6513. Inform via a "preprocessor".  (As Inform became more elaborate, this
  6514. preprocessing might take three stages: high level code such as "objectloop"
  6515. constructs being knocked down to equivalent "while" statements and then to
  6516. assembly language lines.)
  6517.  
  6518. In order to cope with the problem of forward references to labels, Inform
  6519. made two passes through its assembly language source, which is fairly standard
  6520. behaviour for assemblers (because it is easy to implement and has low
  6521. memory overheads).  Yet it became a more and more nightmarish process to
  6522. ensure that high-level constructs would always translate into identical code
  6523. on pass 1 and pass 2, and ever more clear that great effort was being made
  6524. to do a long and difficult calculation twice, burning the result the first
  6525. time.
  6526.  
  6527. Given all this, the wonder is that Inform worked at all.  In fact it worked
  6528. rather well, after a couple of years of polishing and optimisation: although
  6529. slow in theory, profiling runs suggested that the process of translating into
  6530. textual assembly language (for instance) was not a significant speed loss
  6531. (since opcodes could be textually recognised very quickly, while the work
  6532. in parsing operands had been deferred from earlier on, and would have to have
  6533. been done anyway).  Inform performed very rapidly in terms of compilation
  6534. time per source line when compared to typical commercial compilers (which,
  6535. to be fair, were compiling more complex languages) and was unusually low
  6536. in memory consumption.
  6537.  
  6538. This last was a serious issue when Inform was released, as many users were
  6539. running it on machines like 0.5M Amigas.  Without a grown-up syntax analyser,
  6540. there was no need to store large parse trees (such as most compilers do for
  6541. entire routines at a time: the performance of most compilers seriously
  6542. degrades as the length of a single routine increases).
  6543.  
  6544. From Inform 1 to 5.5, the main algorithms and issues never changed, despite
  6545. much reorganisation, renaming, rewriting and extension.  But after two and a
  6546. half years, it had clearly "rusted" badly: it was difficult to maintain or
  6547. work on.  Bugs were appearing which seemed ridiculous in a program so
  6548. established and widely used: for example, not until 1995 did anybody realise
  6549. that division had been accidentally programmed as right, not left associative
  6550. (thus "12/6/2" evaluated to 4, not 1).  An endless mass of ad-hoc rules was
  6551. being added to cover up the lack of proper lexical analysis.  Moreover, the
  6552. major new feature -- the linker -- added another massive complication to an
  6553. already convoluted piece of code.  (I have by now designed and painfully got
  6554. working three different versions of the linker, and would not go through all
  6555. that again for all the tea in China.)
  6556.  
  6557. What began as a general tidying-up and bug-fixing exercise sank into the
  6558. depressing realisation that a total rewrite was the only way to make
  6559. significant progress.  Six months later, the writing of this sentence finally
  6560. completes that task.
  6561.  
  6562.  
  6563.    13.4   Modification history
  6564.           --------------------
  6565.  
  6566.    (i) Changes made between v6.01 and v6.02
  6567.        ------------------------------------
  6568.  
  6569. Features added:
  6570. "Declared but not used" and "no such constant" errors now reported on or near
  6571.     line of occurrence, not at end of source.
  6572. Error message added for local variable being defined twice for the same
  6573.     routine
  6574.  
  6575. Bugs fixed:
  6576. "Segmentation fault" (i.e., writing memory out of range) fixed to do with
  6577.     symbol flags being set wrongly
  6578. Constant binary numbers not lexed correctly
  6579. "for (p = 0::)" misinterpreted due to "::" being recognised as an operator
  6580. Backpatch error under RISC OS (and possibly elsewhere) when linker used
  6581. Grammar token routines reported as "declared but not used"
  6582. Grammar token routines not working at run time
  6583. "ofclass" failing to recognised inherited class membership
  6584. Inheritance of negated attributes not working
  6585. "children" function giving the wrong answer (specifically, always giving the
  6586.     object number of the first child); this had the knock-on effect of
  6587.     making the "tree" debugging verb produce incorrect output
  6588.  
  6589. Source code cleaning:
  6590. Header file rearranged to typedef int32 in the right place, and tidied
  6591.     up a little; ICL_Directory defined rather than left to cause an error
  6592.     when Inform is compiled; INFORM_FILE replaced with MAIN_INFORM_FILE
  6593.     in some of the OS definition blocks; SEEK_SET defined rather than left
  6594.     to the vagaries of ANSI
  6595. Type clashes between int and int32 reconciled for:
  6596.     assemble_label_no, routine_starts_line, read_byte_from_memory_block,
  6597.     write_byte_to_memory_block, parse_label, symbol_index
  6598. Return value for hash_code_from_string cast explicitly to int (rather than
  6599.     implicitly from unsigned int)
  6600. prec_table given type int
  6601. Many "dead assignments" (redundant settings of variables) removed
  6602. "=-" replaced by "= -" to prevent pre-ANSI compilers from misunderstanding
  6603.     "x=-1" as "x=x-1"
  6604. The veneer string for the source of "CA__Pr" has been contracted to make
  6605.     it smaller than 2048 chars long, since Microsoft Visual C/C++ won't
  6606.     compile strings longer than that
  6607. symbs[] explicitly cast to char * in a few points in "linker", "objects" and
  6608.     "symbols"
  6609. Format string for process IDs corrected from "_proc%08x" to "_proc%08lx"
  6610. Format string for serial number copying removed, and a use of strcpy put
  6611.     in its place
  6612.  
  6613.    (ii) Changes made between v6.02 and v6.03
  6614.         ------------------------------------
  6615.  
  6616. Feature added:
  6617. The on/off command-line switches can now be prefixed with ~ to turn them off.
  6618.    (This is useful only in ICL, to undo the effect of previous lines.)
  6619.  
  6620. Bugs fixed:
  6621. The "my parent is Class" value in modules changed from 0xffff to 0x7fff to
  6622.     make it valid in type int (rather than int32)
  6623. The "spaces" statement not being parsed correctly (bug in syntax analyser)
  6624. Arrays declared using Global rather than Array don't work (this is fixed,
  6625.     but also now causes an obsolete usage warning)
  6626. Fclose applied to null file handle (effectively, the same file closed twice)
  6627. "for (::p++)" misinterpreted due to "::" being recognised as an operator
  6628. Some -> -> object initialisations getting the structure wrong
  6629. Table of property names wrongly compiled (resulting in garbled run-time error
  6630.     messages)
  6631. Serious failure of individual property inheritance from a class when both
  6632.     inheritor and class define individual property values
  6633. Messages sent to a property whose value is NULL now do nothing and reply 0
  6634.     (as if the property value were 0)
  6635. Action switches not working in properties called via messages (well, not
  6636.     really a bug: but it's better that they should work, as this makes it
  6637.     possible to call "before"/"after" as messages)
  6638. The "children" inlined routine leaving redundant values on the stack (which
  6639.     resulted in complex expressions containing uses of children()
  6640.     mis-evaluating)
  6641. Actions in the form <A x> and <A x y> using a call opcode improperly (with
  6642.     possibly regrettable results -- though they worked on my interpreter!)
  6643. ICL files not working (due to a bug gratuitously introduced in v6.02), and
  6644.     not understanding tab characters as spaces, and generally being poorly
  6645.     implemented (I found print "Err..."; in the code, to my alarm): generally
  6646.     tidied up now
  6647. Negative constants not working as switch() case values
  6648. Slightly better reporting of bad statement errors, and slightly better
  6649.     recovery
  6650.  
  6651. Source code cleaning:
  6652. Calls to get_next_char() replaced with (*get_next_char)() which is equivalent
  6653.     to a modern ANSI compiler, but inequivalent to a pre-ANSI one
  6654. Logically redundant "break" statements added to parse_routine() to prevent
  6655.     either "unreachable code" or "no return from non-void function" warnings
  6656.     being produced
  6657. parse_given_directive() has its unnecessary parameter removed
  6658. uchar types used for characters as read in by the lexer before filtering takes
  6659.     place to, e.g., strip off any set top bits
  6660.  
  6661.    (iii) Changes made between v6.03 and v6.04
  6662.          ------------------------------------
  6663.  
  6664. Features added:
  6665. When double-quoted text is continued from one source line to another, and
  6666.     the first ends in ^, then the new-line is not replaced by a space " ".
  6667.     Thus:    print "Shall I compare thee to a summer's day?^
  6668.                     Thou art more...";
  6669.     results in the "T" being printed underneath the "S", not one space to the
  6670.     right.
  6671. Statements like
  6672.  
  6673.         "The wyvern swallows ", (the) noun, " in three gulps!";
  6674.  
  6675.     are now correctly understood to be print_ret statements.  (Previously
  6676.     this gave errors because the syntax analyser thought it was going to
  6677.     be a list of three switch cases separated by commas, until it hit the
  6678.     semicolon and realised there should be a colon, by which time it was
  6679.     too late to go back.  The language definition has never been clear
  6680.     on whether long implied print_rets are legal or not, so I've decided
  6681.     that they are.)
  6682. The #n$ construct (for single-character dictionary words) can now take
  6683.     non-alphabetic characters: e.g., #n$1 and #n$# refer to dictionary
  6684.     words '1' and '#'.
  6685.  
  6686. Bugs fixed:
  6687. The Verb "newverb" = "oldverb"; syntax not working, due to mistake in syntax
  6688.     analyser (or rather, to inadequate testing)
  6689. If routine R is being Replaced, then its new definition can now appear either
  6690.     before or after its Library definition (as long as the Replace declaration
  6691.     occurs before both definitions).  In 6.01 to 6.03, errors would result
  6692.     if the new definition was earlier than the Library one.
  6693. Constants not being allowed as switch cases when they happen to be the same as
  6694.     internal statement keywords (such as the single letter "a")
  6695. Memory allocations of 0 bytes now return NULL, which protects Inform from
  6696.     trying to apply "free" to them, which seems to have caused problems on
  6697.     some ports (not on mine, but it was my mistake)
  6698. Spurious "Second 'Ifnot' in same 'If...'" errors appearing in certain
  6699.     nested 'If...' configurations
  6700. A comma in between object headers and bodies is now optional once again (as
  6701.     it used to be in Inform 5), rather than forbidden.
  6702. Text or commentary appearing after a string folding character \ now causes
  6703.     an error, as it should (the rest of such a line should be empty).
  6704. "continue" not properly working inside a "for" loop of the "optimised" kind
  6705.     (that is, whose update code consists of just variable++ or variable--)
  6706. For two different reasons, "or" did not quite work when used in its
  6707.     extended way (i.e. with conditions other than ==, ~= or with many
  6708.     alternatives): apologies, as the code was in a muddle.  Better now.
  6709. Class classname(N) ... was allowing creation of only N-1 new instances,
  6710.     not N.
  6711. (a) not recognised as a print specification when "a" is also the name of
  6712.     a local variable.
  6713. "youngest" function failing to work.
  6714.  
  6715. Source code cleaning:
  6716. Header declarations of the variables "mv_xref" and "no_stubbed_routines"
  6717.     removed (neither one actually exists in the released state of Inform 6)
  6718. Miscellaneous comments added
  6719. Assembly of store opcodes optimised to pull opcodes in a few cases, saving
  6720.     1 byte of object code each time
  6721. Hooks for Robert Pelak's MAC_FACE port (traditionally the most strenuous)
  6722.     inserted
  6723. Error messages reworded slightly for better consistency
  6724.  
  6725.    (iv)  Changes made between v6.04 and v6.05
  6726.          ------------------------------------
  6727.  
  6728. Feature added:
  6729. Assembly language tracing slightly tidied up (a cosmetic change only).
  6730.  
  6731. Bugs fixed:
  6732. When a file with very long strings in (such as one generated automatically
  6733.     by "infoclues") is read, it can corrupt memory, resulting in the malloc
  6734.     heap being damaged.
  6735. Spurious backpatching errors (actually, all backpatching errors are spurious -
  6736.     backpatching is supposed to work every time) produced when the Z-code
  6737.     area of the Z-machine exceeds 64K.  (This seldom happens even in large
  6738.     games, unless quite long print and print_ret strings are quoted.)  The
  6739.     error message in question was
  6740.     
  6741.         *** Backpatch symbol out of range ***
  6742.  
  6743.     and, just to recap, this should never appear. Please send me the
  6744.     offending source code if it persists!
  6745. The only time I've seen this bug is that it once hung the Z-machine while
  6746.     working on printing an inventory of items which needed grouping using
  6747.     "list_together", but it's actually a mistake in the shift-reduce
  6748.     expression grammar: "(...)" (function call) has precedence level 11,
  6749.     whereas "." has level 12, in order to make messages
  6750.             object.message(...)
  6751.     parse correctly (i.e., as (object.message)(...)).  This isn't usually
  6752.     done in SR operator grammars because, as I now realise, it results in
  6753.             function(X).property
  6754.     being misinterpreted as function(X.property).  I've corrected this by
  6755.     giving (...) the asymmetric precedence level of 11 on the right, but
  6756.     14 on the left.
  6757. Printing dictionary contents to a text transcript file not working on the
  6758.     Amiga port, since an internal buffer was overwritten by one byte
  6759.     (5x16+1 = 81, not 80).
  6760. Spurious "variable declared but not used" warnings appearing for a variable
  6761.     used only as a store destination in assembly language.
  6762. The "box" statement producing boxes of the wrong width when the text contains
  6763.     the @ escape character (e.g. "@@92@@92@@92" used to be wrongly
  6764.     calculated as 12 characters wide, when it really consists of three
  6765.     backslash characters).
  6766. The v6.04 optimisation using "pull" (see above) didn't work in v6, v7 or v8
  6767.     (for two different reasons, but basically because the opcode behaves
  6768.     differently in these as compared with lower versions).
  6769. Assembly language in v8 recognising the wrong instruction set (same as
  6770.     the previous bug).
  6771. Version 6 games not properly compiled in some cases (because of a rounding
  6772.     error in calculating packed address offsets: a new section 8.8 has been
  6773.     added to this manual to document how Inform works these out).
  6774.  
  6775.    "I compiled Inform 6.05 under Purify, and am pleased to report that Purify
  6776.     reported exactly 0 memory access errors and 0 bytes of memory leaked."
  6777.     -- Brad Jones
  6778.  
  6779.  
  6780.    (v)  Changes made between v6.05 and v6.10
  6781.         ------------------------------------
  6782.  
  6783. Features added:
  6784. The four ICL path variables which define places to look for input of
  6785.     different kinds (source code, include files, ICL files and modules)
  6786.     can now hold lists of alternative locations, separated by a character
  6787.     called FN_ALT which may be OS-dependant (but is normally ',').
  6788.     These alternatives are tried left-to-right until the desired filename
  6789.     is found.  It's legal for an alternative to be empty, meaning the
  6790.     current position (e.g. "+include_path=,library,oldlib" gives three
  6791.     possible paths -- the current directory, then the library and oldlib
  6792.     subdirectories).  The on-line examples (in the -h1 help information)
  6793.     now include this new feature.
  6794. File and pathnames in ICL and on the command line can now contain spaces
  6795.     if written inside double-quotes: e.g., "Games Folder/New Games" would
  6796.     be a valid ICL pathname.  (Provided for benefit of Macintosh users.)
  6797. A new error message format, -E2, uses Macintosh Programmer's Workshop style.
  6798. Output game files in the MPW port are given the type and creator for the
  6799.     MaxZip interpreter.  (With thanks to Tom Emerson for supplying details.)
  6800. The compiler can now generate a new format of grammar table: if used with
  6801.     old code, it will behave just as it used to, but if used with Library
  6802.     6/3 or later will generate "GV2" (grammar version 2) tables.  Users
  6803.     will notice that several restrictions are lifted, most usefully:
  6804.     
  6805.         the number of tokens per grammar line can be up to 30, not up to 6;
  6806.         the total number of prepositions is now unlimited (it used to be
  6807.             limited to about 80);
  6808.         the total number of routines named in grammar tokens is now
  6809.             unlimited (it used to be limited to 32);
  6810.         the total number of actions per game can be up to 4096, not 256.
  6811.  
  6812.     (Chapter 8 above has been rewritten to document GV1 and GV2 in full.)
  6813.     In addition, there are three new grammar features:
  6814.     (a) you can mark an action as "reverse", as in the following example:
  6815.  
  6816.         Verb 'show' 'present' 'display'
  6817.                 * creature held                  -> Show reverse
  6818.                 * held 'to' creature             -> Show;
  6819.  
  6820.         "reverse" indicating that the two parameters are to be reversed
  6821.         in order before the action is generated.
  6822.     (b) you can give two or more prepositions (only) as alternatives:
  6823.  
  6824.         Verb 'sit' 'lie'
  6825.                 * 'on' 'top' 'of' noun           -> Enter
  6826.                 * 'on'/'in'/'inside' noun        -> Enter;
  6827.  
  6828.         the "/" markers indicating alternative prepositions, any one of
  6829.         which is equally good.
  6830.     (c) there is a new grammar token called "topic", which matches any
  6831.         block of text up to the next preposition or the end of the input.
  6832.         For instance,
  6833.  
  6834.         Verb 'read'
  6835.                 * noun                           -> Examine
  6836.                 * 'about' topic 'in' noun        -> Consult
  6837.                 * topic 'in' noun                -> Consult;
  6838.  
  6839.         It's used mostly for reading material and subjects of conversation,
  6840.         hence the name "topic".  For how to deal with the results of parsing
  6841.         a topic, see the Designer's Manual on "Consult".
  6842.     These three features are only available when using Inform in conjunction
  6843.     with Library 6/3 or later.
  6844. The run-time veneer's implementation has been rewritten, especially in the
  6845.     areas of message-sending and superclass access.  Several benefits:
  6846.     (a) the :: superclass operator can be used with any property
  6847.         (in Inform 6.05 it only worked with individual properties);
  6848.     (b) it makes sense to look up or send to
  6849.  
  6850.             something.Object::cant_go
  6851.  
  6852.         and this refers to the default value of "cant_go".  (So we can
  6853.         think of common properties as being exactly the ones inherited
  6854.         from class Object.)
  6855.     (c) printing out a property name, as in
  6856.     
  6857.             print (property) Crown::colour
  6858.  
  6859.         now correctly prints "Crown::colour".  (Previously it got stuck
  6860.         on superclass properties.)
  6861.     (d) the limits on numbers of things are made more sensible.  These
  6862.         are now as follows:
  6863.         (i) up to 256 classes per game;
  6864.         (ii) up to 128 different individual properties (and up to 63
  6865.              common properties) can be provided by any single object;
  6866.         (iii) up to 32703 individual property names throughout the game.
  6867.         These limits are now enforced by the compiler, which used to
  6868.         lazily not check them.
  6869.     (e) in games using the Inform library, when the variable debug_flag
  6870.         has bottom bit set (the Inform library does this when the
  6871.         "routines" verb has been typed), all messages are traced to
  6872.         the screen.  (Except any messages caused as a result of trying
  6873.         to perform this printing.)  This is fuller and more helpful
  6874.         than the old "routines" output.
  6875.     (Several parts of chapter 9 above have been corrected.)
  6876. The dictionary data structure is entirely redesigned, as a red-black tree
  6877.     rather than a hash table.  The effects of this change are localised
  6878.     to "text.c" (i.e., no other source files were modified to achieve it).
  6879.     For small games no difference will be noticed; for large games there will
  6880.     be a slight speed improvement, becoming more noticeable as the game grows.
  6881.     (E.g.: on my machine "Curses" compiles 4% faster.)  See Section 8.4 above
  6882.     for details.
  6883. As part of a general move toward multilingualism, the notation for dictionary
  6884.     words is extended: 'word//letters' means the word 'word' with some flags
  6885.     attached.  At present, the only such flag is 'p', meaning "plural".
  6886.     Note that 'word//' is legal and equivalent to 'word'.  Thus, 'w//'
  6887.     is another way of making the dictionary word #n$w (which we can't write
  6888.     as 'w' because that's only a single character).
  6889.     (This information is stored in a previously unused flag in #dict_par1:
  6890.     see the bitmap in section 8.5 above.)
  6891. Dictionary words may now contain accented characters (this is likely to be
  6892.     essential for some Scandinavian languages).  It is also now legal to
  6893.     write a quotation mark within quotation marks, in two cases:
  6894.         '''         (meaning: the literal character ')
  6895.         '@'etude'   (to put an acute accent on something)
  6896. To avoid dictionary resolution falling unacceptably when accented chars
  6897.     are used, it's helpful to move commonly occurring ones into the
  6898.     Z-machine alphabets: the new directive "Zcharacter" does this.
  6899.     See section 12.2 above.
  6900. The dictionary contents are now given in alphabetical order in text transcript
  6901.     files, and the "Trace dictionary;" output is much more descriptive.
  6902. Tracing output for calls to functions marked with a * is more legible,
  6903.     giving exactly the arguments supplied and naming embedded routines
  6904.     more sensibly (e.g. as "lantern.time_left" rather than "Embedded__43").
  6905.     The -g switch now traces only the user's own functions, not the library
  6906.     ones, unless -g2 is set.
  6907. Inform now checks for the error of giving the same property twice in one
  6908.     definition.  This is not always as obvious as (say) giving the
  6909.     "description" of an object twice over, because of the existence of
  6910.     aliases.  A typical error message would be:
  6911.  
  6912.          line 15: Error: Property given twice in the same declaration,
  6913.          because the names 'initial' and 'when_open' actually refer
  6914.          to the same property
  6915.  
  6916. A warning is produced if the "box" statement is used in a Version 3 game
  6917.     (since it cannot have any effect in such a game).
  6918. The default memory allocation for arrays has been increased (from 4000 to
  6919.     10000 bytes).  The original was too conservative, and anyway more will
  6920.     be needed for language definition files in library 6/3.
  6921. Action and attribute names are now written into story files, so that it's
  6922.     possible to print them (for debugging purposes).  Full details of how
  6923.     to do this are in section 9.6 above.  (Users with library 6/3 may notice
  6924.     that the "actions" debugging verb now names all actions, not just the
  6925.     ones defined by the library.)
  6926. Inform now allows the three special constants DEBUG, USE_MODULES and
  6927.     MODULE_MODE to be defined more than once without giving an error.
  6928.     Thus, if your code contains "Constant DEBUG;" already, but you
  6929.     compile it with the "-D" option anyway, no error will be produced.
  6930. When an object isn't given a textual name, rather than calling it "?"
  6931.     Inform now calls it something like "(red_box)", where "red_box" is
  6932.     its internal symbol name.  (This makes debugging output easier to
  6933.     follow and wastes very few bytes.)  When the object hasn't got an
  6934.     internal name either (if it's defined just as "Object;" for
  6935.     example) it has the textual name "(102)", 102 being its object number.
  6936.  
  6937. Bugs fixed:
  6938. "Extend only ..." not always parsed correctly, sometimes giving a spurious
  6939.     syntax error, other times failing to notice "first/last/replace".
  6940. In -U mode, failure to report as an error a line consisting of two words, the
  6941.     first of which is a constant or variable name defined in a previously
  6942.     linked module.  (This arose when the line "Action RevTakeWith" was
  6943.     accidentally written instead of "Fake_action RevTakeWith" -- what
  6944.     happened was that "Action" was recognised as the variable "action",
  6945.     which Inform knew was a symbol exported from a linked module (ParserM);
  6946.     it took this value as a class, wrongly, and made a new object called
  6947.     RevTakeWith of this "class".  The fault was in the syntax analyser,
  6948.     which wrongly assumed that it wouldn't necessarily be known whether an
  6949.     exported symbol was a class-name or not, and so allowed all exported
  6950.     symbols to be used, just to be on the safe side.)
  6951. ICL fatal error messages quoting a garbled filename.
  6952. Version 3 games (ah, remember them?) not compiling because of the usage of
  6953.     call opcodes not present in the V3 Z-machine
  6954. The "Include ">name"" feature not working when the original source file
  6955.     lies at the current working directory of the host OS, rather than in
  6956.     some subdirectory.
  6957. The linker had a rarely-occurring bug which prevented the tasks scoring
  6958.     system from working properly in a game which linked rather than included
  6959.     the library modules: if an instruction wrote a value to certain variables
  6960.     whose internal numbers were in a certain narrow range, then these
  6961.     variables would not be correctly reconciled with the story file variables
  6962.     at link time.  This same bug possibly also accounts for an even rarer
  6963.     occurrence, which I've had no definite report of, in which the less than
  6964.     professional error message "Ooops" is produced.  (I've corrected the
  6965.     error message to something more helpful.)
  6966. Rather seriously (though this error took a long time to be found),
  6967.     if (condition) rfalse; else ... [or the same thing with rtrue;]
  6968.     producing syntax errors.  (A mistake in some optimisation code.)
  6969. The "elder" function wrongly returning 0.
  6970. Not always reporting errors when global variables were used wrongly as
  6971.     values of object properties or array elements.  (Sometimes a backpatch
  6972.     error would be given.)  These are now properly parsed in constant
  6973.     context, not quantity context.
  6974. Spurious warning about code not being reachable at the close brace of
  6975.     a "for" loop, when this is indeed not reachable.  (It can still be
  6976.     sensible code, if the idea is always to "continue" or "return"
  6977.     from the body of the loop.)
  6978. When the error "Error: System function name used as value "child"" is
  6979.     produced, also printing a spurious *** Emit token error *** message.
  6980. Backpatch errors sometimes produced when compiling a line (in a module only)
  6981.     which contains an "if" condition making heavy use of "or".
  6982. Code backpatch errors sometimes produced when the condition "ofclass" is
  6983.     compiled.
  6984. '->' or 'Nearby' mysteriously failing if the parent object referred to
  6985.     was (a) defined in a module and (b) one of the first four objects
  6986.     defined there.
  6987. "Declared but not used" warnings issued for replacements of routines
  6988.     only accessed from within a linked module.
  6989. Error message if a non-existent ICL variable set, not being printed.
  6990.  
  6991. Source code cleaning:
  6992. A port definition called PC_WIN32 has been added to "header.h", courtesy of
  6993.     Kirk Klobe.
  6994. Two variables made int32 instead of int (thanks to Evan Day for spotting
  6995.     the desirability of this).
  6996. The veneer routines are segmented so that no individual literal string
  6997.     is as long as 512 characters.  (An irritating requirement imposed by
  6998.     the Macintosh port's compiler.)
  6999. Six miscellaneous explicit casts of (char *) to (uchar *), suggested by
  7000.     Robert Pelak.  More systematically, the opcode names in asm.c are all
  7001.     explicitly cast to (uchar *).
  7002. A slight change to inform.c makes the Mac front end's arrangement (of
  7003.     calling only sub_main(), while main() itself is not compiled) more
  7004.     generally usable by other ports: see section 2.2 (e).
  7005.  
  7006.  
  7007.    (vi)  Changes made between v6.10 and v6.11
  7008.          ------------------------------------
  7009.  
  7010. Bugs fixed:
  7011. An important one -- the optimised form of statements like
  7012.     if (variable) rfalse;
  7013.     was being negated, i.e., was being wrongly compiled as
  7014.     if (~~variable) rfalse;
  7015.     (In Library 6/3, this showed up at one stage as odd behaviour when
  7016.     moving around in darkness.)
  7017. The statement "spaces 0" printing infinitely many spaces instead of
  7018.     doing nothing.  (Negative arguments have always done nothing.)  It is
  7019.     possible to provoke this behaviour in calls to the list-writer.
  7020. Bug to do with parsing quoted filenames in ICL.
  7021. Spurious "declared but not used" warning for global variables used only
  7022.     in a module being linked in.
  7023.  
  7024. Source code cleaning:
  7025. Atari ST definition block updated on advice of Charles Briscoe-Smith.
  7026. Copyright dates nudged on to 1997.
  7027. Paranoid test added when closing temporary files.
  7028. Macintosh interface code added on advice of Robert Pelak.
  7029. Two long printfs subdivided to assist poor compilers.
  7030. String subdivision in "CA__Pr" in the veneer moved slightly in a way
  7031.     which makes no logical difference, but which seems to fix a mysterious
  7032.     problem observed by Robert Pelak (possibly with his compiler: it has
  7033.     been observed on no other platform).
  7034. Text transcript file is now opened as a text file, not a binary file,
  7035.     which will hopefully assist some ports but inconvenience nobody.
  7036.     (All the same, it may be worth testing that text transcripts still
  7037.     look sensible on your port.)  Code added to the Macintosh port to
  7038.     ensure closure of the file if compilation aborts.
  7039.  
  7040.  
  7041.    (vii)  Changes made between v6.11 and v6.12
  7042.           ------------------------------------
  7043.  
  7044. Feature added:
  7045. A new switch, -C, and the ability to read source code files in any
  7046.     ISO 8859 standard extension to the ASCII character set.  The
  7047.     default is ISO 8859-1, Latin1, the standard character set on
  7048.     most computers in most European countries.  This means that
  7049.     many accented characters can simply be typed directly, a
  7050.     particular advantage with exotic ISO ranges (Arabic, Hebrew,
  7051.     Greek, Cyrillic, etc.).  If your computer is unable to use any
  7052.     of 8859-1 to -9, the -C0 switch (for plain ASCII only) can be
  7053.     used.  Accent markers such as '@:u' (for u-diaeresis) remain
  7054.     valid, just as usual, but a new string escape '@{..hex number..}'
  7055.     allows the specification of any Unicode character.  For instance
  7056.     '@{a9}' produces a copyright sign (Unicode values between $0000
  7057.     and $00ff are equal to ISO Latin1 values), and '@{2657}' produces
  7058.     in principle a White bishop chess symbol.  In practice, if you
  7059.     wish to use rare Unicode symbols, you'll need an interpreter
  7060.     obeying the Z-Machine Standard 1.0, and you'll probably have
  7061.     to supply it with an appropriate font as well; also, any characters
  7062.     not normally resident in the Z-machine need to be declared in
  7063.     advance of use with the "Zcharacter table" directive.  But if
  7064.     you're only using (e.g.) ordinary German, Spanish or French
  7065.     accents the new facilities will work with any Standard 0.2
  7066.     interpreter.
  7067.     The "Zcharacter" directive, for configuring the Z-machine to
  7068.     use non-English alphabets, is greatly enhanced.
  7069.     (In the Z-machine, Inform now always generates a header extension
  7070.     table, and sometimes uses a slot within it to point to a Unicode
  7071.     translation table newly specified in Standard 1.0.)
  7072. The debugging information file has finally been brought up to date with
  7073.     Inform 6, and old code inherited from Inform 5 (the only such
  7074.     code in the whole compiler) has been cleaned out.  The main change
  7075.     is in producing source-code-to-PC-value maps, which is made more
  7076.     difficult by the compression of code at the end of each routine.
  7077.     The exact format will probably change: this release is an interim
  7078.     one, to assist development of Infix.
  7079. The concept of sequence points has been introduced, to assist Infix.
  7080.  
  7081. Bugs fixed:
  7082. Not a bug as such, but the veneer implementation has been changed so that
  7083.     class-objects never have attributes set.  In 6.01 to 6.11, a class
  7084.     object like Monster might have the attribute "animate" and would
  7085.     therefore be picked up in objectloops over all animate objects, and
  7086.     so on.  This is undesirable, and illogical since after all class
  7087.     objects don't provide any properties, so why have attributes?
  7088.     Anyway, the result means that objectloops of the form
  7089.     
  7090.         objectloop (x has <attribute>)  ...
  7091.  
  7092.     will now not range through classes but only genuine game objects.
  7093. When compound Boolean conditions are used as expressions (for instance,
  7094.     in an assignment like "x = (y>1) || d;") the wrong answers could
  7095.     result if the top operator was ||.  (If it was &&, or if the
  7096.     condition had no &&s or ||s in, or if the condition was being used
  7097.     as a test rather than a numerical value, everything was normal.)
  7098. Fake actions being defined before grammar version is set were causing
  7099.     mysterious problems.  This would happen if the Fake_Action directive
  7100.     were used before "Parser" is included.  An error message has been
  7101.     added advising that Fake_Action directives should be moved.
  7102.     (Fake actions are now mostly obsolete anyway.)
  7103. Any attributes aliased together being given the unhelpful name
  7104.     "<unknown attribute>" in output from the "showobj" debugging verb.
  7105. Backpatch *** errors *** sometimes being produced as a knock-on effect
  7106.     from already-reported linkage errors.  (These *** errors *** are
  7107.     now suppressed if linkage has already broken down.)
  7108. The character codes for << and >> (Continental European quotation marks)
  7109.     were the wrong way around, following a mistake in version 0.2 of
  7110.     the Z-Machine Standards document.  They have therefore been
  7111.     swapped over, following the correction made in version 1.0 of that
  7112.     document.
  7113. Accented characters deep inside dictionary words sometimes getting lost.
  7114.     (Because of an ambiguity in the Standards document where Inform
  7115.     made the wrong choice, but interpreters made the right one.)
  7116. The -w (suppress warnings) switch doing nothing.  (In writing Inform 6
  7117.     I simply forgot this.)
  7118.  
  7119. Source code cleaning:
  7120. A new UNIX64 port, for 64-bit Unix machines, added (courtesy of Magnus
  7121.     Olsson) which should subtract pointers correctly even in the unlikely
  7122.     event that they lie in different 2^32 byte pages.  Otherwise identical
  7123.     to UNIX.
  7124. And a new BEOS port added (courtesy of Michael van Biesbrouck) but which is
  7125.     identical to the Linux one in all but name.
  7126. Link error message handling, and character error message handling,
  7127.     slightly more automated.
  7128. The "Compiled with %d errors and %d warnings" message reworded so as not
  7129.     to mention 0 of anything, and to indicate how many warnings were
  7130.     suppressed (by the -q or -w switches).
  7131. The table of memory settings is now printed more prettily in response
  7132.     to the ICL command $list.
  7133. A new memory setting, MAX_LABELS, has been added, along with error checking
  7134.     to test for too many label points in any single routine.
  7135. Various functions to do with character set handling tidied up and moved
  7136.     into the new section "chars.c".
  7137.  
  7138.  
  7139.    (viii)  Changes made between v6.12 and v6.13
  7140.            ------------------------------------
  7141. Bug fixed:
  7142. String escapes in the form "You can't go @00 from here." not working
  7143.     (slip of the keyboard when re-writing string escapes in v6.12).
  7144.  
  7145. Source code cleaning:
  7146. The type of alphabet[][] has been altered so as to ensure that the
  7147.     contents are not read-only strings:
  7148.     from    char *alphabet[3]    to    char alphabet[3][27].
  7149.  
  7150.  
  7151.    (ix)  Changes made between v6.13 and v6.14
  7152.          ------------------------------------
  7153.  
  7154. Bugs fixed:
  7155. "Parker's disease": In very large games only, backpatch errors being
  7156.     caused because the Z-code area of the Z-machine had overflowed
  7157.     past the size where the compiler could backpatch it (this tended
  7158.     to happen only if large amounts of text were printed by Inform code
  7159.     rather than being property values).  The Inform code generator now
  7160.     automatically writes any string of text longer than 32 characters
  7161.     into the static strings area: designers shouldn't notice any difference
  7162.     in behaviour of the "print" or "print_ret" statements.
  7163.     (The new arrangement is fractionally wasteful of bytes -- about
  7164.     2 to 4 bytes per string in excess of 32 characters -- but makes
  7165.     a big difference to the relative sizes of the code and strings
  7166.     areas.  "Advent" compiled the old way was 60.1% code, 17.3% strings;
  7167.     the new way, it comes out 40.6% code, 37.1% strings and is about
  7168.     1K bigger.  Most of the change occurs when compiling library
  7169.     messages; the effects are less dramatic on typical Inform code.)
  7170. A different cause of backpatch errors is attempting to link Version 5 modules
  7171.     into a Version 8 game.  If you're compiling a V8 game and want to
  7172.     link in the library, for instance, you'll need to compile the
  7173.     library modules with "-v8" as well.  Inform used not to check this
  7174.     error condition, but now does produce an error message if there's
  7175.     a version mismatch between game and module.
  7176. The linker also now checks that module and game are using the same
  7177.     Z-machine character set.  (If either one has made a Zcharacter directive
  7178.     which differs from the other, then the sets are inconsistent and
  7179.     linkage can't take place.  This will only ever happen if you're
  7180.     working in a language other than English, and trying to use the linker,
  7181.     and it can be cured by copying the Zcharacter directives out of the
  7182.     language definition file into a little include file, and including
  7183.     that in the source for your main file as well as the source for any
  7184.     modules of your own -- i.e., any modules other than the library ones.)
  7185. Finally, the linker checks for the error condition that the module asked
  7186.     to import a variable which turns out not to have been defined in the
  7187.     main game.  (This may cause problems in linking with library 6/6, as
  7188.     Inform is now able to detect an error in 6/6's "linklv.h" which it
  7189.     previously wasn't able to detect: delete the line reading
  7190.     "Import global gender_and_number;" from "linklv.h" if so.)
  7191. "continue" not working (branching to the non-existent label -1, in
  7192.     fact) if used inside a "switch" statement.  (It ought to continue
  7193.     the innermost loop containing the "switch" statement, if there is
  7194.     one, or give an error if there isn't.)
  7195. The two string escapes @@94 (producing a ^ character) and @@126
  7196.     (producing ~) in fact producing new-line and double-quote.
  7197. Conditional branches to rtrue or rfalse in assembly-language being
  7198.     reversed in sense.
  7199. Source code being garbled after any Include statement which ends at
  7200.     a byte position which is a multiple of 4096, minus 3.  (My thanks
  7201.     to Andrew Plotkin for both finding and diagnosing this.)
  7202. "For" loops in the form "for ( : : )" (with white space between the two
  7203.     colons), which occur in a routine after a previous one which happens
  7204.     to have a designer-defined label in a particular position, causing
  7205.     an incorrect if harmless "Label declared but not used" warning.
  7206. Very short programs testing "x provides <property>", but never reading,
  7207.     writing or otherwise using <property>, causing stack overflows or
  7208.     restarts.  Nobody would ever need such a program anyway.
  7209. Function calls not working, or having garbled arguments, in Version 3
  7210.     or Version 4 games (the Inform library requires Version 5 or better
  7211.     nowadays, so the ability to compile V3 or V4 files is only needed
  7212.     for interpreter testing).
  7213. The error message disallowing use of an assembly opcode if the Z-machine
  7214.     version doesn't support it, now quotes the opcode name.
  7215. Suppressed "declared but not used" warnings for global objects not being
  7216.     counted towards the total number reported as suppressed when Inform
  7217.     prints its final message.
  7218.  
  7219. Source code cleaning:
  7220. Three character conversions amended to unsigned character conversions.
  7221. Backpatch errors, which I devoutly hope not to see again, are now
  7222.     reported as a new category of error: "compiler errors" which produce
  7223.     an apologetic banner, asking the user to report the fault to me.
  7224. Link errors are reported more prettily (differently, anyway).
  7225.  
  7226.  
  7227.    (x)  Acknowledgements
  7228.         ----------------
  7229.  
  7230. Many thanks to the following informers, who have reported bugs in Inform 6:
  7231.  
  7232.     Torbj|rn Andersson, Jose Luis Diaz de Arriba, Paul E. Bell,
  7233.     Michael van Biesbrouck, Gerald Bostock, Neil Brown, Russ Bryan,
  7234.     Jesse Burneko, Evan Day, Stephen van Egmond, Tom Emerson, Greg Falcon,
  7235.     Roy Fellows, Rob Fisher, David Fletcher, C. E. Forman, Richard Gault,
  7236.     Paul Gilbert, Michael Graham, Bjorn Gustavsson, Andreas Hoppler,
  7237.     Sam Hulick, Brad Jones, Christoffer Karlsson, Niclas Karlsson,
  7238.     John Kennedy, Matt Kimball, Kirk Klobe, Michael A. Krehan, Mary Kuhner,
  7239.     Josh Larios, Harvey Lodder, Bonni Mierzejewska, Tim Muddleton,
  7240.     Olav Mueller, Ross Nicol, Magnus Olsson, Marnie Parker, Robert Pelak,
  7241.     Aphoristic Petrofsky, Andrew Plotkin, Fredrik Ramsberg, Matthew Russotto,
  7242.     Miron Schmidt, Rene Schnoor, Nyuchezuu Shampoo, Anson Turner,
  7243.     Uncle Bob Newell and all.
  7244.  
  7245. ------------------------------------------------------------------------------
  7246.